mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-25 11:06:12 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6deb62379 | ||
|
|
895eff09b0 | ||
|
|
d0252f7179 | ||
|
|
d78c13fce3 | ||
|
|
6bb5200464 | ||
|
|
a02a2f5799 | ||
|
|
63c23c98de | ||
|
|
9a90b94921 | ||
|
|
f03418afde | ||
|
|
19d0009891 | ||
|
|
9fc85ae9db | ||
|
|
2e4b2c82f4 | ||
|
|
a9042a58ab | ||
|
|
244ec6c8f7 | ||
|
|
e28471e0ad | ||
|
|
778d5b675c | ||
|
|
127113188e |
@@ -716,7 +716,7 @@ export const protocol = Protocol.make({
|
||||
reasoningSignatures: {},
|
||||
}),
|
||||
step,
|
||||
onHalt,
|
||||
onHalt: (state) => Effect.succeed(onHalt(state)),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -718,7 +718,7 @@ export const protocol = Protocol.make({
|
||||
lifecycle: Lifecycle.initial(),
|
||||
}),
|
||||
step,
|
||||
onHalt: finish,
|
||||
onHalt: (state) => Effect.succeed(finish(state)),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -285,6 +285,7 @@ export const Event = Schema.StructWithRest(
|
||||
Schema.Struct({
|
||||
type: Schema.String,
|
||||
delta: Schema.optional(Schema.String),
|
||||
arguments: Schema.optional(Schema.String),
|
||||
text: Schema.optional(Schema.String),
|
||||
item_id: Schema.optional(Schema.String),
|
||||
summary_index: Schema.optional(Schema.Number),
|
||||
@@ -996,12 +997,24 @@ const onFunctionCallArgumentsDelta = Effect.fn("OpenResponses.onFunctionCallArgu
|
||||
state: ParserState,
|
||||
event: Event,
|
||||
) {
|
||||
if (!event.item_id || !event.delta || !state.tools[event.item_id]) return [state, NO_EVENTS] satisfies StepResult
|
||||
if (!event.item_id) return [state, NO_EVENTS] satisfies StepResult
|
||||
const tool = state.tools[event.item_id]
|
||||
if (!tool) return [state, NO_EVENTS] satisfies StepResult
|
||||
const final = event.type === "response.function_call_arguments.done" ? event.arguments : undefined
|
||||
if (event.type === "response.function_call_arguments.done" && final === undefined)
|
||||
return [state, NO_EVENTS] satisfies StepResult
|
||||
if (final !== undefined && !final.startsWith(tool.input))
|
||||
return [
|
||||
{ ...state, tools: ToolStream.start(state.tools, event.item_id, { ...tool, input: final }) },
|
||||
NO_EVENTS,
|
||||
] satisfies StepResult
|
||||
const delta = final === undefined ? event.delta : final.slice(tool.input.length)
|
||||
if (!delta) return [state, NO_EVENTS] satisfies StepResult
|
||||
const result = ToolStream.appendExisting(
|
||||
state.id,
|
||||
state.tools,
|
||||
event.item_id,
|
||||
event.delta,
|
||||
delta,
|
||||
`${state.name} tool argument delta is missing its tool call`,
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
@@ -1212,7 +1225,7 @@ export const step = (state: ParserState, event: Event) => {
|
||||
return ProviderShared.eventError(state.id, `${event.type} message is missing id`)
|
||||
return Effect.succeed(onOutputItemAdded(state, event))
|
||||
}
|
||||
if (event.type === "response.function_call_arguments.delta")
|
||||
if (event.type === "response.function_call_arguments.delta" || event.type === "response.function_call_arguments.done")
|
||||
return event.item_id
|
||||
? onFunctionCallArgumentsDelta(state, event)
|
||||
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
|
||||
|
||||
@@ -7,7 +7,10 @@ import { HttpTransport } from "../route/transport/index.js"
|
||||
import { Protocol } from "../route/protocol.js"
|
||||
import {
|
||||
AIError,
|
||||
InvalidProviderOutputReason,
|
||||
LLMEvent,
|
||||
ProviderInternalReason,
|
||||
UnknownProviderReason,
|
||||
Usage,
|
||||
type FinishReason,
|
||||
type FinishReasonDetails,
|
||||
@@ -224,16 +227,22 @@ const OpenAIChatChoice = Schema.StructWithRest(
|
||||
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||
)
|
||||
|
||||
const OpenAIChatError = Schema.Struct({
|
||||
code: optionalNull(Schema.Union([Schema.String, Schema.Number])),
|
||||
message: Schema.String,
|
||||
})
|
||||
const OpenAIChatError = Schema.StructWithRest(
|
||||
Schema.Struct({
|
||||
code: optionalNull(Schema.Union([Schema.String, Schema.Number])),
|
||||
message: Schema.String,
|
||||
}),
|
||||
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||
)
|
||||
|
||||
export const OpenAIChatEvent = Schema.Struct({
|
||||
choices: optionalNull(Schema.Array(OpenAIChatChoice)),
|
||||
usage: optionalNull(OpenAIChatUsage),
|
||||
error: optionalNull(OpenAIChatError),
|
||||
})
|
||||
export const OpenAIChatEvent = Schema.StructWithRest(
|
||||
Schema.Struct({
|
||||
choices: optionalNull(Schema.Array(OpenAIChatChoice)),
|
||||
usage: optionalNull(OpenAIChatUsage),
|
||||
error: optionalNull(OpenAIChatError),
|
||||
}),
|
||||
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||
)
|
||||
export type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
|
||||
type OpenAIChatRequestMessage = LLMRequest["messages"][number]
|
||||
|
||||
@@ -256,6 +265,7 @@ export interface ParserState {
|
||||
readonly reasoningEmitted: boolean
|
||||
readonly latestToolIndex?: number
|
||||
readonly nextToolIndex: number
|
||||
readonly requireFinishReason: boolean
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -726,14 +736,40 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||
// Streaming parsers are small state machines: every event returns a new state
|
||||
// plus the common `LLMEvent`s produced by that event. Tool calls are accumulated
|
||||
// because OpenAI streams JSON arguments across multiple deltas.
|
||||
const mapFinishReason = (reason: string | null | undefined): FinishReason => {
|
||||
if (reason === "stop") return "stop"
|
||||
if (reason === "length") return "length"
|
||||
if (reason === "content_filter") return "content-filter"
|
||||
if (reason === "function_call" || reason === "tool_calls") return "tool-calls"
|
||||
if (reason === "error") return "error"
|
||||
return "unknown"
|
||||
}
|
||||
const finishReasonError = (event: OpenAIChatEvent, reason: AIError["reason"]) =>
|
||||
new AIError({
|
||||
module: ADAPTER,
|
||||
method: "stream",
|
||||
body: ProviderShared.encodeJson(event),
|
||||
reason,
|
||||
})
|
||||
|
||||
const mapFinishReason = Effect.fn("OpenAIChat.mapFinishReason")(function* (event: OpenAIChatEvent, reason: string) {
|
||||
switch (reason) {
|
||||
case "error":
|
||||
return yield* finishReasonError(
|
||||
event,
|
||||
new UnknownProviderReason({ message: "Provider reported an error (finish_reason: error)" }),
|
||||
)
|
||||
case "network_error":
|
||||
return yield* finishReasonError(
|
||||
event,
|
||||
new ProviderInternalReason({ message: "Provider reported a network error (finish_reason: network_error)" }),
|
||||
)
|
||||
case "stop":
|
||||
case "end":
|
||||
return "stop" as const
|
||||
case "length":
|
||||
return "length" as const
|
||||
case "content_filter":
|
||||
return "content-filter" as const
|
||||
case "function_call":
|
||||
case "tool_calls":
|
||||
return "tool-calls" as const
|
||||
default:
|
||||
return "unknown" as const
|
||||
}
|
||||
})
|
||||
|
||||
// OpenAI Chat reports `prompt_tokens` (inclusive total) with a
|
||||
// cached-read and cache-write subsets, and `completion_tokens` (inclusive
|
||||
@@ -846,16 +882,20 @@ const reasoningMetadata = (field: ParserState["reasoningField"], details?: Reado
|
||||
|
||||
const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.error)
|
||||
if (event.error) {
|
||||
const body = ProviderShared.encodeJson(event)
|
||||
return yield* new AIError({
|
||||
module: ADAPTER,
|
||||
method: "stream",
|
||||
body,
|
||||
reason: classifyProviderFailure({
|
||||
message: event.error.message,
|
||||
code: event.error.code === undefined || event.error.code === null ? undefined : String(event.error.code),
|
||||
status: typeof event.error.code === "number" ? event.error.code : undefined,
|
||||
rawBody: body,
|
||||
}),
|
||||
})
|
||||
}
|
||||
const events: LLMEvent[] = []
|
||||
const choice = event.choices?.[0]
|
||||
// Moonshot (and a few other OpenAI-compatible providers) attach usage to
|
||||
@@ -864,8 +904,11 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
const usage = mapUsage(event.usage) ?? (choiceUsage ? mapUsage(choiceUsage) : undefined) ?? state.usage
|
||||
const rawFinishReason = choice?.finish_reason
|
||||
const finishReason =
|
||||
rawFinishReason !== undefined && rawFinishReason !== null
|
||||
? { normalized: mapFinishReason(rawFinishReason), raw: choice?.native_finish_reason ?? rawFinishReason }
|
||||
rawFinishReason
|
||||
? {
|
||||
normalized: yield* mapFinishReason(event, rawFinishReason),
|
||||
raw: choice?.native_finish_reason ?? rawFinishReason,
|
||||
}
|
||||
: state.finishReason
|
||||
const delta = choice?.delta
|
||||
const toolDeltas = delta?.tool_calls ?? []
|
||||
@@ -885,7 +928,11 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
toolDeltas.some((tool) => Boolean(tool.id) || Boolean(tool.function?.name) || Boolean(tool.function?.arguments))
|
||||
if (state.finishReason !== undefined) {
|
||||
if (hasLateContent)
|
||||
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat received content after the finish reason")
|
||||
return yield* ProviderShared.eventError(
|
||||
ADAPTER,
|
||||
"OpenAI Chat received content after the finish reason",
|
||||
ProviderShared.encodeJson(event),
|
||||
)
|
||||
return [{ ...state, usage }, events] as const
|
||||
}
|
||||
|
||||
@@ -957,14 +1004,19 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
{ id: id || undefined, name: name || undefined, text },
|
||||
"OpenAI Chat tool call delta is missing id or name",
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
if (ToolStream.isError(result))
|
||||
return yield* ProviderShared.eventError(ADAPTER, result.reason.message, ProviderShared.encodeJson(event))
|
||||
tools = result.tools
|
||||
if (result.events.length) lifecycle = Lifecycle.stepStart(lifecycle, events)
|
||||
events.push(...result.events)
|
||||
}
|
||||
|
||||
if (finishReason !== undefined && state.finishReason === undefined && Object.keys(pendingTools).length > 0)
|
||||
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat tool call delta is missing id or name")
|
||||
return yield* ProviderShared.eventError(
|
||||
ADAPTER,
|
||||
"OpenAI Chat tool call delta is missing id or name",
|
||||
ProviderShared.encodeJson(event),
|
||||
)
|
||||
|
||||
// Finalize accumulated tool inputs eagerly when finish_reason arrives so
|
||||
// valid calls and malformed local calls settle independently.
|
||||
@@ -987,16 +1039,27 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
reasoningEmitted,
|
||||
latestToolIndex,
|
||||
nextToolIndex,
|
||||
requireFinishReason: state.requireFinishReason,
|
||||
},
|
||||
events,
|
||||
] as const
|
||||
})
|
||||
|
||||
const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
||||
const finishEvents = Effect.fn("OpenAIChat.finishEvents")(function* (state: ParserState) {
|
||||
if (state.finishReason === undefined && state.requireFinishReason)
|
||||
return yield* new AIError({
|
||||
module: ADAPTER,
|
||||
method: "stream",
|
||||
reason: new InvalidProviderOutputReason({
|
||||
classification: "incomplete-stream",
|
||||
message: "OpenAI Chat stream ended without finish_reason",
|
||||
route: ADAPTER,
|
||||
}),
|
||||
})
|
||||
const events: LLMEvent[] = []
|
||||
const toolCallEvents =
|
||||
state.finishReason === undefined && Object.keys(state.tools).length > 0
|
||||
? Effect.runSync(ToolStream.finishAll(ADAPTER, state.tools)).events
|
||||
? (yield* ToolStream.finishAll(ADAPTER, state.tools)).events
|
||||
: state.toolCallEvents
|
||||
const hasToolCalls = toolCallEvents.length > 0
|
||||
const reason = state.finishReason
|
||||
@@ -1005,7 +1068,7 @@ const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
||||
normalized:
|
||||
state.finishReason.normalized === "stop" && hasToolCalls ? "tool-calls" : state.finishReason.normalized,
|
||||
}
|
||||
: { normalized: hasToolCalls ? ("tool-calls" as const) : ("unknown" as const) }
|
||||
: { normalized: hasToolCalls ? ("tool-calls" as const) : ("stop" as const) }
|
||||
const metadata = reasoningMetadata(
|
||||
state.reasoningField,
|
||||
state.reasoningDetailsObserved ? state.reasoningDetails : undefined,
|
||||
@@ -1019,7 +1082,7 @@ const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
||||
events.push(...toolCallEvents)
|
||||
Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
|
||||
return events
|
||||
}
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// Protocol And OpenAI Route
|
||||
@@ -1048,6 +1111,7 @@ export const protocol = Protocol.make({
|
||||
reasoningDetailsObserved: false,
|
||||
reasoningEmitted: false,
|
||||
nextToolIndex: 0,
|
||||
requireFinishReason: request.model.compatibility?.requireFinishReason ?? true,
|
||||
}),
|
||||
step,
|
||||
onHalt: finishEvents,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Adapted from partial-json by the Promplate Dev Team:
|
||||
* https://github.com/promplate/partial-json-parser-js/blob/main/src/options.ts
|
||||
* Licensed under the MIT License; see partial-json.ts for the complete notice.
|
||||
*/
|
||||
|
||||
/**
|
||||
* allow partial strings like `"hello \u12` to be parsed as `"hello `
|
||||
*/
|
||||
export const STR = 0b000000001
|
||||
|
||||
/**
|
||||
* allow partial numbers like `123.` to be parsed as `123`
|
||||
*/
|
||||
export const NUM = 0b000000010
|
||||
|
||||
/**
|
||||
* allow partial arrays like `[1, 2,` to be parsed as `[1, 2]`
|
||||
*/
|
||||
export const ARR = 0b000000100
|
||||
|
||||
/**
|
||||
* allow partial objects like `{"a": 1, "b":` to be parsed as `{"a": 1}`
|
||||
*/
|
||||
export const OBJ = 0b000001000
|
||||
|
||||
/**
|
||||
* allow `nu` to be parsed as `null`
|
||||
*/
|
||||
export const NULL = 0b000010000
|
||||
|
||||
/**
|
||||
* allow `tr` to be parsed as `true`, and `fa` to be parsed as `false`
|
||||
*/
|
||||
export const BOOL = 0b000100000
|
||||
|
||||
/**
|
||||
* allow `Na` to be parsed as `NaN`
|
||||
*/
|
||||
export const NAN = 0b001000000
|
||||
|
||||
/**
|
||||
* allow `Inf` to be parsed as `Infinity`
|
||||
*/
|
||||
export const INFINITY = 0b010000000
|
||||
|
||||
/**
|
||||
* allow `-Inf` to be parsed as `-Infinity`
|
||||
*/
|
||||
export const _INFINITY = 0b100000000
|
||||
|
||||
export const INF = INFINITY | _INFINITY
|
||||
export const SPECIAL = NULL | BOOL | INF | NAN
|
||||
export const ATOM = STR | NUM | SPECIAL
|
||||
export const COLLECTION = ARR | OBJ
|
||||
export const ALL = ATOM | COLLECTION
|
||||
|
||||
/**
|
||||
* Control what types you allow to be partially parsed.
|
||||
* The default is to allow all types to be partially parsed, which in most cases is the best option.
|
||||
*/
|
||||
export const Allow = { STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, _INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL }
|
||||
|
||||
export default Allow
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* Adapted from partial-json by the Promplate Dev Team:
|
||||
* https://github.com/promplate/partial-json-parser-js
|
||||
*
|
||||
* MIT License
|
||||
*
|
||||
* Copyright (c) 2023 Promplate Dev Team
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
import { Schema } from "effect"
|
||||
import { Allow } from "./partial-json-options.js"
|
||||
export * from "./partial-json-options.js"
|
||||
|
||||
export class PartialJSON extends Error {}
|
||||
export class MalformedJSON extends Error {}
|
||||
|
||||
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown))
|
||||
|
||||
/** Parse complete or incomplete JSON, restricted by the supplied partial-value flags. */
|
||||
export function parseJSON(jsonString: string, allowPartial = Allow.ALL): unknown {
|
||||
if (typeof jsonString !== "string") throw new TypeError(`expecting str, got ${typeof jsonString}`)
|
||||
const input = jsonString.trim()
|
||||
if (!input) throw new Error(`${jsonString} is empty`)
|
||||
try {
|
||||
return decodeJson(input)
|
||||
} catch {}
|
||||
return _parseJSON(input, allowPartial)
|
||||
}
|
||||
|
||||
const _parseJSON = (jsonString: string, allow: number) => {
|
||||
const length = jsonString.length
|
||||
let index = 0
|
||||
|
||||
const markPartialJSON = (message: string): never => {
|
||||
throw new PartialJSON(`${message} at position ${index}`)
|
||||
}
|
||||
|
||||
const throwMalformedError = (message: string): never => {
|
||||
throw new MalformedJSON(`${message} at position ${index}`)
|
||||
}
|
||||
|
||||
const parseAny = (): unknown => {
|
||||
skipBlank()
|
||||
if (index >= length) markPartialJSON("Unexpected end of input")
|
||||
if (jsonString[index] === '"') return parseStr()
|
||||
if (jsonString[index] === "{") return parseObj()
|
||||
if (jsonString[index] === "[") return parseArr()
|
||||
if (
|
||||
jsonString.substring(index, index + 4) === "null" ||
|
||||
(Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 4
|
||||
return null
|
||||
}
|
||||
if (
|
||||
jsonString.substring(index, index + 4) === "true" ||
|
||||
(Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 4
|
||||
return true
|
||||
}
|
||||
if (
|
||||
jsonString.substring(index, index + 5) === "false" ||
|
||||
(Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 5
|
||||
return false
|
||||
}
|
||||
if (
|
||||
jsonString.substring(index, index + 8) === "Infinity" ||
|
||||
(Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 8
|
||||
return Infinity
|
||||
}
|
||||
if (
|
||||
jsonString.substring(index, index + 9) === "-Infinity" ||
|
||||
(Allow._INFINITY & allow &&
|
||||
1 < length - index &&
|
||||
length - index < 9 &&
|
||||
"-Infinity".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 9
|
||||
return -Infinity
|
||||
}
|
||||
if (
|
||||
jsonString.substring(index, index + 3) === "NaN" ||
|
||||
(Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index)))
|
||||
) {
|
||||
index += 3
|
||||
return NaN
|
||||
}
|
||||
return parseNum()
|
||||
}
|
||||
|
||||
const parseStr = (): string => {
|
||||
const start = index
|
||||
let escape = false
|
||||
index++
|
||||
while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === "\\"))) {
|
||||
escape = jsonString[index] === "\\" ? !escape : false
|
||||
index++
|
||||
}
|
||||
if (jsonString.charAt(index) === '"') {
|
||||
try {
|
||||
return decodeJson(jsonString.substring(start, ++index - Number(escape))) as string
|
||||
} catch (error) {
|
||||
throwMalformedError(String(error))
|
||||
}
|
||||
}
|
||||
if (Allow.STR & allow) {
|
||||
try {
|
||||
return decodeJson(`${jsonString.substring(start, index - Number(escape))}"`) as string
|
||||
} catch {
|
||||
return decodeJson(`${jsonString.substring(start, jsonString.lastIndexOf("\\"))}"`) as string
|
||||
}
|
||||
}
|
||||
return markPartialJSON("Unterminated string literal")
|
||||
}
|
||||
|
||||
const parseObj = (): Record<string, unknown> => {
|
||||
index++
|
||||
skipBlank()
|
||||
const object: Record<string, unknown> = {}
|
||||
try {
|
||||
while (jsonString[index] !== "}") {
|
||||
skipBlank()
|
||||
if (index >= length && Allow.OBJ & allow) return object
|
||||
const key = parseStr()
|
||||
skipBlank()
|
||||
index++
|
||||
try {
|
||||
object[key] = parseAny()
|
||||
} catch (error) {
|
||||
if (Allow.OBJ & allow) return object
|
||||
throw error
|
||||
}
|
||||
skipBlank()
|
||||
if (jsonString[index] === ",") index++
|
||||
}
|
||||
} catch {
|
||||
if (Allow.OBJ & allow) return object
|
||||
return markPartialJSON("Expected '}' at end of object")
|
||||
}
|
||||
index++
|
||||
return object
|
||||
}
|
||||
|
||||
const parseArr = (): unknown[] => {
|
||||
index++
|
||||
const array: unknown[] = []
|
||||
try {
|
||||
while (jsonString[index] !== "]") {
|
||||
array.push(parseAny())
|
||||
skipBlank()
|
||||
if (jsonString[index] === ",") index++
|
||||
}
|
||||
} catch {
|
||||
if (Allow.ARR & allow) return array
|
||||
return markPartialJSON("Expected ']' at end of array")
|
||||
}
|
||||
index++
|
||||
return array
|
||||
}
|
||||
|
||||
const parseNum = (): unknown => {
|
||||
if (index === 0) {
|
||||
if (jsonString === "-") throwMalformedError("Not sure what '-' is")
|
||||
try {
|
||||
return decodeJson(jsonString)
|
||||
} catch (error) {
|
||||
if (Allow.NUM & allow) {
|
||||
try {
|
||||
return decodeJson(jsonString.substring(0, jsonString.lastIndexOf("e")))
|
||||
} catch {}
|
||||
}
|
||||
throwMalformedError(String(error))
|
||||
}
|
||||
}
|
||||
|
||||
const start = index
|
||||
if (jsonString[index] === "-") index++
|
||||
while (jsonString[index] && !",]}".includes(jsonString[index])) index++
|
||||
if (index === length && !(Allow.NUM & allow)) markPartialJSON("Unterminated number literal")
|
||||
|
||||
try {
|
||||
return decodeJson(jsonString.substring(start, index))
|
||||
} catch (error) {
|
||||
if (jsonString.substring(start, index) === "-") markPartialJSON("Not sure what '-' is")
|
||||
try {
|
||||
return decodeJson(jsonString.substring(start, jsonString.lastIndexOf("e")))
|
||||
} catch {
|
||||
throwMalformedError(String(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const skipBlank = () => {
|
||||
while (index < length && " \n\r\t".includes(jsonString[index])) index++
|
||||
}
|
||||
|
||||
return parseAny()
|
||||
}
|
||||
|
||||
export const parse = parseJSON
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Effect } from "effect"
|
||||
import { Effect, Option } from "effect"
|
||||
import { AIError, LLMEvent, type ProviderMetadata, type ToolCall, type ToolInputError } from "../../schema/index.js"
|
||||
import { eventError, parseToolInput, type ToolAccumulator } from "../shared.js"
|
||||
import { parse } from "./partial-json.js"
|
||||
|
||||
type StreamKey = string | number
|
||||
const parsePartialInput = Option.liftThrowable(parse)
|
||||
|
||||
/**
|
||||
* One pending streamed tool call. Providers emit the tool identity and JSON
|
||||
@@ -57,12 +59,15 @@ const inputStart = (tool: PendingTool) =>
|
||||
providerMetadata: tool.providerMetadata,
|
||||
})
|
||||
|
||||
const inputDelta = (tool: PendingTool, text: string) =>
|
||||
LLMEvent.toolInputDelta({
|
||||
const inputDelta = (tool: PendingTool, text: string) => {
|
||||
const input = parsePartialInput(tool.input)
|
||||
return LLMEvent.toolInputDelta({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
text,
|
||||
...(Option.isSome(input) ? { input: input.value } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
||||
const raw = inputOverride ?? tool.input
|
||||
|
||||
@@ -321,12 +321,30 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
|
||||
Stream.mapEffect(decodeEvent(route)),
|
||||
protocol.stream.terminal ? Stream.takeUntil(protocol.stream.terminal) : (stream) => stream,
|
||||
)
|
||||
const stream = events.pipe(
|
||||
Stream.mapAccumEffect(
|
||||
() => protocol.stream.initial(request),
|
||||
protocol.stream.step,
|
||||
protocol.stream.onHalt ? { onHalt: protocol.stream.onHalt } : undefined,
|
||||
),
|
||||
const stream = Stream.suspend(() => {
|
||||
let state = protocol.stream.initial(request)
|
||||
const parsed = events.pipe(
|
||||
Stream.mapEffect((event) =>
|
||||
protocol.stream.step(state, event).pipe(
|
||||
Effect.map(([next, output]) => {
|
||||
state = next
|
||||
return output
|
||||
}),
|
||||
),
|
||||
),
|
||||
Stream.flatMap(Stream.fromIterable),
|
||||
)
|
||||
const onHalt = protocol.stream.onHalt
|
||||
return onHalt
|
||||
? parsed.pipe(
|
||||
Stream.concat(
|
||||
Stream.suspend(() =>
|
||||
Stream.unwrap(onHalt(state).pipe(Effect.map(Stream.fromIterable))),
|
||||
),
|
||||
),
|
||||
)
|
||||
: parsed
|
||||
}).pipe(
|
||||
Stream.catchCause((cause) => Stream.fail(streamError(route, `Failed to read ${route} stream`, cause))),
|
||||
requireTerminalEvent(route),
|
||||
)
|
||||
|
||||
@@ -59,8 +59,8 @@ export interface ProtocolStream<Frame, Event, State> {
|
||||
readonly step: (state: State, event: Event) => Effect.Effect<readonly [State, ReadonlyArray<LLMEvent>], AIError>
|
||||
/** Optional request-completion signal for transports that do not end naturally. */
|
||||
readonly terminal?: (event: Event) => boolean
|
||||
/** Optional flush emitted when the framed stream ends. */
|
||||
readonly onHalt?: (state: State) => ReadonlyArray<LLMEvent>
|
||||
/** Optional effectful flush emitted when the framed stream ends. */
|
||||
readonly onHalt?: (state: State) => Effect.Effect<ReadonlyArray<LLMEvent>, AIError>
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -152,6 +152,8 @@ export const ToolInputDelta = Schema.Struct({
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
text: Schema.String,
|
||||
/** Best-effort parse of all input fragments received through this delta. */
|
||||
input: Schema.optional(Schema.Unknown),
|
||||
}).annotate({ identifier: "LLM.Event.ToolInputDelta" })
|
||||
export type ToolInputDelta = Schema.Schema.Type<typeof ToolInputDelta>
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Allow, MalformedJSON, PartialJSON, parse } from "../src/protocols/utils/partial-json.js"
|
||||
|
||||
describe("partial JSON", () => {
|
||||
test("parses complete JSON", () => {
|
||||
expect(parse('{"key":"value","items":[1,true,null]}')).toEqual({
|
||||
key: "value",
|
||||
items: [1, true, null],
|
||||
})
|
||||
|
||||
const object = parse('{"__proto__":{"safe":true}}') as Record<string, unknown>
|
||||
expect(Object.hasOwn(object, "__proto__")).toBe(true)
|
||||
})
|
||||
|
||||
test("parses partial strings", () => {
|
||||
expect(parse('"hello')).toBe("hello")
|
||||
expect(parse('"hello \\u12')).toBe("hello ")
|
||||
expect(() => parse('"hello', ~Allow.STR)).toThrow(PartialJSON)
|
||||
})
|
||||
|
||||
test("controls partial collection values independently", () => {
|
||||
expect(parse('["', Allow.ARR)).toEqual([])
|
||||
expect(parse('["', Allow.ARR | Allow.STR)).toEqual([""])
|
||||
expect(parse('{"key":"', Allow.OBJ)).toEqual({})
|
||||
expect(parse('{"key":"', Allow.OBJ | Allow.STR)).toEqual({ key: "" })
|
||||
})
|
||||
|
||||
test("parses partial literals and numbers", () => {
|
||||
expect(parse("nu", Allow.NULL)).toBeNull()
|
||||
expect(parse("tr", Allow.BOOL)).toBe(true)
|
||||
expect(parse("fa", Allow.BOOL)).toBe(false)
|
||||
expect(parse("1e", Allow.NUM)).toBe(1)
|
||||
})
|
||||
|
||||
test("distinguishes disallowed partial values from malformed values", () => {
|
||||
expect(() => parse("[", Allow.STR)).toThrow(PartialJSON)
|
||||
expect(() => parse("n", ~Allow.NULL)).toThrow(MalformedJSON)
|
||||
})
|
||||
|
||||
test("rejects empty input", () => {
|
||||
expect(() => parse(" ")).toThrow("is empty")
|
||||
})
|
||||
})
|
||||
@@ -585,12 +585,11 @@ describe("Anthropic Messages route", () => {
|
||||
|
||||
it.effect("infers empty-signature compatibility across Kimi providers", () =>
|
||||
Effect.gen(function* () {
|
||||
const coding = AnthropicMessages.route
|
||||
.with({
|
||||
provider: "kimi-for-coding",
|
||||
endpoint: { baseURL: "https://compatible.test/v1/" },
|
||||
auth: Auth.header("x-api-key", "test"),
|
||||
})
|
||||
const coding = AnthropicMessages.route.with({
|
||||
provider: "kimi-for-coding",
|
||||
endpoint: { baseURL: "https://compatible.test/v1/" },
|
||||
auth: Auth.header("x-api-key", "test"),
|
||||
})
|
||||
const moonshot = AnthropicMessages.route
|
||||
.with({
|
||||
provider: "moonshotai",
|
||||
@@ -1129,8 +1128,14 @@ describe("Anthropic Messages route", () => {
|
||||
expect(response.events).toEqual([
|
||||
{ type: "step-start", index: 0 },
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: ':"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||
{
|
||||
type: "tool-call",
|
||||
|
||||
@@ -475,8 +475,14 @@ describe("Bedrock Converse route", () => {
|
||||
])
|
||||
const events = response.events.filter((event) => event.type === "tool-input-delta")
|
||||
expect(events).toEqual([
|
||||
{ type: "tool-input-delta", id: "tool_1", name: "lookup", text: '{"query"' },
|
||||
{ type: "tool-input-delta", id: "tool_1", name: "lookup", text: ':"weather"}' },
|
||||
{ type: "tool-input-delta", id: "tool_1", name: "lookup", text: '{"query"', input: {} },
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "tool_1",
|
||||
name: "lookup",
|
||||
text: ':"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
])
|
||||
expect(response.events.at(-1)).toMatchObject({
|
||||
type: "finish",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AmazonBedrockMantle } from "../../src/providers.js"
|
||||
import { compileRequest, LLMClient } from "../../src/route/client.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
import { dynamicResponse } from "../lib/http.js"
|
||||
import { sseEvents } from "../lib/sse.js"
|
||||
import { recordedTests } from "../recorded-test.js"
|
||||
|
||||
const credentials = {
|
||||
@@ -71,7 +72,9 @@ describe("Amazon Bedrock Mantle provider", () => {
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpClientRequest.toWeb(input.request)
|
||||
seen.push({ url: request.url, authorization: request.headers.get("authorization") ?? undefined })
|
||||
return input.respond("", { headers: { "content-type": "text/event-stream" } })
|
||||
return input.respond(sseEvents({ choices: [{ delta: {}, finish_reason: "stop" }] }), {
|
||||
headers: { "content-type": "text/event-stream" },
|
||||
})
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1164,8 +1164,14 @@ describe("OpenAI Chat route", () => {
|
||||
expect(response.events).toEqual([
|
||||
{ type: "step-start", index: 0 },
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: ':"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||
{
|
||||
type: "tool-call",
|
||||
@@ -1245,6 +1251,11 @@ describe("OpenAI Chat route", () => {
|
||||
).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
|
||||
|
||||
expect(error.message).toContain("OpenAI Chat tool call delta is missing id or name")
|
||||
expect(error.reason._tag).toBe("InvalidProviderOutput")
|
||||
if (error.reason._tag !== "InvalidProviderOutput") return
|
||||
expect(decodeJson(error.reason.raw ?? "")).toMatchObject({
|
||||
choices: [{ finish_reason: "tool_calls" }],
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1258,6 +1269,7 @@ describe("OpenAI Chat route", () => {
|
||||
deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
|
||||
)
|
||||
const input = LLMRequest.update(request, {
|
||||
model: LanguageModel.update(model, { compatibility: { requireFinishReason: false } }),
|
||||
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
|
||||
})
|
||||
const response = yield* LLMClient.generate(input).pipe(Effect.provide(fixedResponse(body)))
|
||||
@@ -1265,8 +1277,14 @@ describe("OpenAI Chat route", () => {
|
||||
expect(response.events).toEqual([
|
||||
{ type: "step-start", index: 0 },
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: ':"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||
{
|
||||
type: "tool-call",
|
||||
|
||||
@@ -353,13 +353,106 @@ describe("OpenAI-compatible Chat route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("treats an empty finish reason as terminal", () =>
|
||||
it.effect("rejects a stream without a required finish reason", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* LLMClient.generate(request).pipe(
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({ content: "Hello" }), deltaChunk({}, "")))),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error.reason).toMatchObject({
|
||||
_tag: "InvalidProviderOutput",
|
||||
classification: "incomplete-stream",
|
||||
message: "OpenAI Chat stream ended without finish_reason",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("infers stop when finish reasons are optional", () =>
|
||||
Effect.gen(function* () {
|
||||
const compatible = OpenAICompatibleChat.route
|
||||
.with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } })
|
||||
.model({ id: "custom-model", compatibility: { requireFinishReason: false } })
|
||||
const response = yield* LLMClient.generate(LLMRequest.update(request, { model: compatible })).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({ content: "Hello" }), deltaChunk({}, "")))),
|
||||
)
|
||||
|
||||
expect(response.finishReason).toEqual({ normalized: "unknown", raw: "" })
|
||||
expect(response.finishReason).toEqual({ normalized: "stop" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("normalizes the end finish reason to stop", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({ content: "Hello" }), deltaChunk({}, "end")))),
|
||||
)
|
||||
|
||||
expect(response.finishReason).toEqual({ normalized: "stop", raw: "end" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies provider error finish reasons", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({}, "network_error")))),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error.reason).toMatchObject({
|
||||
_tag: "ProviderInternal",
|
||||
message: "Provider reported a network error (finish_reason: network_error)",
|
||||
})
|
||||
expect(decodeJson(error.body ?? "")).toMatchObject({
|
||||
id: "chatcmpl_fixture",
|
||||
choices: [{ finish_reason: "network_error" }],
|
||||
})
|
||||
|
||||
const generic = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({}, "error")))),
|
||||
Effect.flip,
|
||||
)
|
||||
expect(generic.reason).toMatchObject({
|
||||
_tag: "UnknownProvider",
|
||||
message: "Provider reported an error (finish_reason: error)",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("preserves explicit provider error events", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(
|
||||
sseEvents({
|
||||
id: "chatcmpl_error",
|
||||
error: { code: 502, message: "Provider disconnected", details: { upstream: "vendor" } },
|
||||
trace_id: "trace_1",
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error.reason).toMatchObject({ _tag: "ProviderInternal", message: "Provider disconnected", status: 502 })
|
||||
expect(decodeJson(error.body ?? "")).toMatchObject({
|
||||
id: "chatcmpl_error",
|
||||
error: { code: 502, message: "Provider disconnected", details: { upstream: "vendor" } },
|
||||
trace_id: "trace_1",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("preserves provider finish outcomes in the common reason algebra", () =>
|
||||
Effect.gen(function* () {
|
||||
const filtered = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({}, "content_filter")))),
|
||||
)
|
||||
const future = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(deltaChunk({}, "future_reason")))),
|
||||
)
|
||||
|
||||
expect(filtered.finishReason).toEqual({ normalized: "content-filter", raw: "content_filter" })
|
||||
expect(future.finishReason).toEqual({ normalized: "unknown", raw: "future_reason" })
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -379,6 +472,11 @@ describe("OpenAI-compatible Chat route", () => {
|
||||
)
|
||||
|
||||
expect(error.message).toContain("OpenAI Chat received content after the finish reason")
|
||||
expect(error.reason._tag).toBe("InvalidProviderOutput")
|
||||
if (error.reason._tag !== "InvalidProviderOutput") return
|
||||
expect(decodeJson(error.reason.raw ?? "")).toMatchObject({
|
||||
choices: [{ delta: { tool_calls: [{ id: "call_1" }] } }],
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1986,6 +1986,11 @@ describe("OpenAI Responses route", () => {
|
||||
item_id: "fc_missing",
|
||||
delta: '{"orphaned":true}',
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_missing",
|
||||
arguments: '{"orphaned":true}',
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
),
|
||||
),
|
||||
@@ -1998,22 +2003,22 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects function argument deltas without the spec-required item id", () =>
|
||||
it.effect("rejects function argument events without the spec-required item id", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(
|
||||
sseEvents(
|
||||
{ type: "response.function_call_arguments.delta", delta: "{}" },
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
const events = [
|
||||
{ type: "response.function_call_arguments.delta", delta: "{}" },
|
||||
{ type: "response.function_call_arguments.done", arguments: "{}" },
|
||||
]
|
||||
|
||||
expect(error.reason._tag).toBe("InvalidProviderOutput")
|
||||
expect(error.message).toContain("response.function_call_arguments.delta is missing item_id")
|
||||
for (const event of events) {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(fixedResponse(sseEvents(event, { type: "response.completed", response: { id: "resp_1" } }))),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error.reason._tag).toBe("InvalidProviderOutput")
|
||||
expect(error.message).toContain(`${event.type} is missing item_id`)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -2806,12 +2811,14 @@ describe("OpenAI Responses route", () => {
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: '{"query"',
|
||||
input: {},
|
||||
},
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: ':"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
{
|
||||
type: "tool-input-end",
|
||||
@@ -2855,6 +2862,172 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("emits only missing function arguments from the arguments done event", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
},
|
||||
{ type: "response.function_call_arguments.delta", item_id: "fc_item_1", delta: '{"query"' },
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_item_1",
|
||||
arguments: '{"query":"weather"}',
|
||||
},
|
||||
{
|
||||
type: "response.output_item.done",
|
||||
item: {
|
||||
type: "function_call",
|
||||
id: "fc_item_1",
|
||||
call_id: "call_1",
|
||||
name: "lookup",
|
||||
arguments: '{"query":"weather"}',
|
||||
},
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.filter((event) => event.type === "tool-input-delta")).toEqual([
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}', input: { query: "weather" } },
|
||||
])
|
||||
expect(response.events.filter(LLMEvent.is.toolInputEnd)).toHaveLength(1)
|
||||
expect(response.events.filter(LLMEvent.is.toolCall)).toEqual([
|
||||
{
|
||||
type: "tool-call",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
input: { query: "weather" },
|
||||
providerExecuted: undefined,
|
||||
providerMetadata: { openai: { itemId: "fc_item_1" } },
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("streams complete function arguments supplied only by the arguments done event", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_item_1",
|
||||
arguments: '{"query":"weather"}',
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.filter((event) => event.type === "tool-input-delta")).toEqual([
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: '{"query":"weather"}',
|
||||
input: { query: "weather" },
|
||||
},
|
||||
])
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({ input: { query: "weather" } })
|
||||
expect(response.finishReason.normalized).toBe("tool-calls")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("does not repeat function arguments already supplied by deltas", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.delta",
|
||||
item_id: "fc_item_1",
|
||||
delta: '{"query":"weather"}',
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_item_1",
|
||||
arguments: '{"query":"weather"}',
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.filter((event) => event.type === "tool-input-delta")).toHaveLength(1)
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({ input: { query: "weather" } })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("uses authoritative arguments done input without emitting a mismatched delta", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.delta",
|
||||
item_id: "fc_item_1",
|
||||
delta: '{"query":"streamed"}',
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_item_1",
|
||||
arguments: '{"query":"final"}',
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.filter((event) => event.type === "tool-input-delta")).toEqual([
|
||||
{
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: '{"query":"streamed"}',
|
||||
input: { query: "streamed" },
|
||||
},
|
||||
])
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({ input: { query: "final" } })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("lets completed output item arguments override the arguments done event", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
item: { type: "function_call", id: "fc_item_1", call_id: "call_1", name: "lookup", arguments: "" },
|
||||
},
|
||||
{
|
||||
type: "response.function_call_arguments.done",
|
||||
item_id: "fc_item_1",
|
||||
arguments: '{"query":"arguments-done"}',
|
||||
},
|
||||
{
|
||||
type: "response.output_item.done",
|
||||
item: {
|
||||
type: "function_call",
|
||||
id: "fc_item_1",
|
||||
call_id: "call_1",
|
||||
name: "lookup",
|
||||
arguments: '{"query":"output-item-done"}',
|
||||
},
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({ input: { query: "output-item-done" } })
|
||||
expect(response.events.filter(LLMEvent.is.toolCall)).toHaveLength(1)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("finalizes a pending function call at response completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
|
||||
@@ -23,9 +23,11 @@ describe("ToolStream", () => {
|
||||
|
||||
expect(first.events).toEqual([
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
|
||||
])
|
||||
expect(second.events).toEqual([
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}', input: { query: "weather" } },
|
||||
])
|
||||
expect(second.events).toEqual([{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' }])
|
||||
expect(finished).toEqual({
|
||||
tools: {},
|
||||
events: [
|
||||
@@ -36,6 +38,45 @@ describe("ToolStream", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("exposes cumulative partial string values", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = ToolStream.appendOrStart(
|
||||
ADAPTER,
|
||||
ToolStream.empty<number>(),
|
||||
0,
|
||||
{ id: "call_1", name: "lookup", text: '{"query":"wea' },
|
||||
"missing tool",
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
|
||||
expect(result.events.at(-1)).toEqual({
|
||||
type: "tool-input-delta",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
text: '{"query":"wea',
|
||||
input: { query: "wea" },
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("omits partial input when the accumulated value cannot be parsed", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = ToolStream.appendOrStart(
|
||||
ADAPTER,
|
||||
ToolStream.empty<number>(),
|
||||
0,
|
||||
{ id: "call_1", name: "lookup", text: "x" },
|
||||
"missing tool",
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
|
||||
expect(result.events).toEqual([
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: "x" },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("keeps accumulated identity when later deltas contain empty strings", () =>
|
||||
Effect.gen(function* () {
|
||||
const first = ToolStream.appendOrStart(
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { expect, test, type Page } from "@playwright/test"
|
||||
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||
import { base64Encode } from "@opencode-ai/util/encode"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
import { expectAppVisible } from "../utils/waits"
|
||||
|
||||
const directory = "C:/OpenCode/SessionQueueRegression"
|
||||
const projectID = "proj_session_queue_regression"
|
||||
const sessionID = "ses_session_queue_regression"
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
|
||||
type InboxRow = {
|
||||
id: string
|
||||
sessionID: string
|
||||
timeCreated: number
|
||||
type: "user"
|
||||
payload: { text: string; metadata?: Record<string, unknown> }
|
||||
delivery: "steer" | "queue"
|
||||
}
|
||||
|
||||
function createQueueMock(seed: string[]) {
|
||||
const rows: InboxRow[] = seed.map((text, index) => ({
|
||||
id: `inb_seed_${index + 1}`,
|
||||
sessionID,
|
||||
timeCreated: 1700000000000 + index,
|
||||
type: "user",
|
||||
payload: { text },
|
||||
delivery: "queue",
|
||||
}))
|
||||
const events: OpenCodeEvent[] = []
|
||||
const prompts: Record<string, unknown>[] = []
|
||||
const changes: { inboxID: string; action: "cancel" | "steer" }[] = []
|
||||
const log: string[] = []
|
||||
let sequence = 0
|
||||
const emit = (type: OpenCodeEvent["type"], data: OpenCodeEvent["data"]) => {
|
||||
sequence += 1
|
||||
events.push({
|
||||
id: `evt_queue_${sequence}`,
|
||||
type,
|
||||
created: Date.now(),
|
||||
durable: { aggregateID: sessionID, seq: sequence, version: 1 },
|
||||
data,
|
||||
} as OpenCodeEvent)
|
||||
}
|
||||
return {
|
||||
rows,
|
||||
prompts,
|
||||
changes,
|
||||
log,
|
||||
events: () => events.splice(0),
|
||||
onPrompt: (input: { sessionID: string; body: Record<string, unknown> }) => {
|
||||
prompts.push(input.body)
|
||||
log.push(`prompt:${String(input.body.delivery ?? "steer")}`)
|
||||
const row: InboxRow = {
|
||||
id: typeof input.body.id === "string" ? input.body.id : `inb_mock_${sequence}`,
|
||||
sessionID: input.sessionID,
|
||||
timeCreated: Date.now(),
|
||||
type: "user",
|
||||
payload: {
|
||||
text: typeof input.body.text === "string" ? input.body.text : "",
|
||||
...(input.body.metadata === undefined ? {} : { metadata: input.body.metadata as Record<string, unknown> }),
|
||||
},
|
||||
delivery: input.body.delivery === "queue" ? "queue" : "steer",
|
||||
}
|
||||
rows.push(row)
|
||||
emit("session.inbox.enqueued", {
|
||||
sessionID: input.sessionID,
|
||||
inboxID: row.id,
|
||||
item: { type: "user", payload: row.payload, delivery: row.delivery },
|
||||
})
|
||||
},
|
||||
onInboxChange: (input: { sessionID: string; inboxID: string; action: "cancel" | "steer" }) => {
|
||||
changes.push({ inboxID: input.inboxID, action: input.action })
|
||||
log.push(`${input.action}:${input.inboxID}`)
|
||||
const index = rows.findIndex((row) => row.id === input.inboxID)
|
||||
const row = rows[index]
|
||||
if (!row) return
|
||||
if (input.action === "cancel") {
|
||||
rows.splice(index, 1)
|
||||
emit("session.inbox.cancelled", { sessionID: input.sessionID, inboxID: input.inboxID })
|
||||
return
|
||||
}
|
||||
row.delivery = "steer"
|
||||
emit("session.inbox.delivery.changed", {
|
||||
sessionID: input.sessionID,
|
||||
inboxID: input.inboxID,
|
||||
delivery: "steer",
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(page: Page, mock: ReturnType<typeof createQueueMock>, followUpBehavior?: "queue" | "steer") {
|
||||
if (followUpBehavior) {
|
||||
await page.addInitScript(
|
||||
(behavior) => localStorage.setItem("settings.v3", JSON.stringify({ general: { followUpBehavior: behavior } })),
|
||||
followUpBehavior,
|
||||
)
|
||||
}
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: projectID,
|
||||
worktree: directory,
|
||||
vcs: "git",
|
||||
name: "session-queue-regression",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
sandboxes: [],
|
||||
},
|
||||
provider: {
|
||||
all: [
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
models: { "queue-model": { id: "queue-model", name: "Queue Model", limit: { context: 200_000 } } },
|
||||
},
|
||||
],
|
||||
connected: ["opencode"],
|
||||
default: { providerID: "opencode", modelID: "queue-model" },
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
id: sessionID,
|
||||
slug: "session-queue-regression",
|
||||
projectID,
|
||||
directory,
|
||||
title: "Session queue regression",
|
||||
version: "dev",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
sessionStatus: () => ({ [sessionID]: { type: "running" } }),
|
||||
inbox: () => mock.rows.map((row) => ({ ...row, payload: { ...row.payload } })),
|
||||
onPrompt: mock.onPrompt,
|
||||
onInboxChange: mock.onInboxChange,
|
||||
events: mock.events,
|
||||
})
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
const composer = page.locator('[data-component="composer"]')
|
||||
await expectAppVisible(composer)
|
||||
return {
|
||||
composer,
|
||||
input: composer.locator('[data-component="composer-editor"]'),
|
||||
rows: page.locator('[data-component="session-queue-row"]'),
|
||||
}
|
||||
}
|
||||
|
||||
test("follow-up preference controls Enter while Mod+Enter uses the alternate delivery", async ({ page }) => {
|
||||
const mock = createQueueMock([])
|
||||
const view = await openSession(page, mock, "queue")
|
||||
|
||||
await view.input.fill("queue this follow-up")
|
||||
await expect(view.composer.locator('[data-action="composer-alternate-delivery"]')).toContainText("Steer")
|
||||
await view.input.press("Enter")
|
||||
await expect(view.rows.getByText("queue this follow-up", { exact: true })).toBeVisible()
|
||||
|
||||
await view.input.fill("steer this correction")
|
||||
await view.input.press("ControlOrMeta+Enter")
|
||||
await expect.poll(() => mock.prompts.map((prompt) => prompt.delivery)).toEqual(["queue", "steer"])
|
||||
await expect(view.input).toHaveText("")
|
||||
})
|
||||
|
||||
test("dragging reorders queued prompts", async ({ page }) => {
|
||||
const mock = createQueueMock(["first queued prompt", "second queued prompt", "third queued prompt"])
|
||||
const view = await openSession(page, mock)
|
||||
await expect(view.rows).toHaveCount(3)
|
||||
|
||||
const first = view.rows.filter({ hasText: "first queued prompt" })
|
||||
const third = view.rows.filter({ hasText: "third queued prompt" })
|
||||
await first.getByRole("button", { name: "Reorder queued prompt" }).hover()
|
||||
await page.mouse.down()
|
||||
const target = await third.boundingBox()
|
||||
if (!target) throw new Error("The target queue row is not visible")
|
||||
await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 10 })
|
||||
await page.mouse.up()
|
||||
|
||||
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText([
|
||||
"second queued prompt",
|
||||
"third queued prompt",
|
||||
"first queued prompt",
|
||||
])
|
||||
expect(mock.prompts.map((prompt) => prompt.text)).toEqual([
|
||||
"second queued prompt",
|
||||
"third queued prompt",
|
||||
"first queued prompt",
|
||||
])
|
||||
expect(mock.changes).toEqual([
|
||||
{ inboxID: "inb_seed_1", action: "cancel" },
|
||||
{ inboxID: "inb_seed_2", action: "cancel" },
|
||||
{ inboxID: "inb_seed_3", action: "cancel" },
|
||||
])
|
||||
})
|
||||
|
||||
test("editing restores the existing draft and replaces only the original queue position", async ({ page }) => {
|
||||
const mock = createQueueMock(["first queued prompt", "tighten the error copy", "third queued prompt"])
|
||||
const view = await openSession(page, mock)
|
||||
const original = view.rows.getByText("tighten the error copy", { exact: true })
|
||||
await expect(original).toBeVisible()
|
||||
|
||||
await view.input.fill("my in-progress draft")
|
||||
await original.click()
|
||||
await expect(view.input).toHaveText("tighten the error copy")
|
||||
await view.input.press("Escape")
|
||||
await expect(view.input).toHaveText("my in-progress draft")
|
||||
|
||||
await original.click()
|
||||
await expect(view.input).toHaveText("tighten the error copy")
|
||||
await view.input.fill("tighten the error copy and add a retry hint")
|
||||
await view.input.press("Enter")
|
||||
|
||||
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText([
|
||||
"first queued prompt",
|
||||
"tighten the error copy and add a retry hint",
|
||||
"third queued prompt",
|
||||
])
|
||||
await expect(view.input).toHaveText("my in-progress draft")
|
||||
expect(mock.prompts.map((prompt) => prompt.text)).toEqual([
|
||||
"tighten the error copy and add a retry hint",
|
||||
"tighten the error copy and add a retry hint",
|
||||
"third queued prompt",
|
||||
])
|
||||
expect(mock.prompts.every((prompt) => prompt.delivery === "queue" && prompt.resume === false)).toBe(true)
|
||||
expect(mock.changes.map((change) => change.action)).toEqual(["cancel", "cancel", "cancel"])
|
||||
expect(mock.log[0]).toBe("prompt:queue")
|
||||
})
|
||||
@@ -59,12 +59,12 @@ test("transitions a streaming shell from writing through command execution", asy
|
||||
await expect(tool.locator('[data-slot="collapsible-trigger"]')).toHaveCSS("height", "28px")
|
||||
await expect(tool.locator('[data-component="tool-trigger"]')).toHaveCSS("gap", "6px")
|
||||
await expect(title).toHaveCSS("font-size", "13px")
|
||||
await expect(title).toHaveCSS("font-family", "Inter, sans-serif")
|
||||
await expect(title).toHaveCSS("font-family", /^Inter,/)
|
||||
await expect(title).toHaveCSS("font-weight", "530")
|
||||
await expect(title).toHaveCSS("line-height", "16px")
|
||||
await expect(title).toHaveCSS("color", "rgb(22, 22, 22)")
|
||||
await expect(subtitle).toHaveCSS("font-size", "13px")
|
||||
await expect(subtitle).toHaveCSS("font-family", "Inter, sans-serif")
|
||||
await expect(subtitle).toHaveCSS("font-family", /^Inter,/)
|
||||
await expect(subtitle).toHaveCSS("font-weight", "440")
|
||||
await expect(subtitle).toHaveCSS("line-height", "16px")
|
||||
await expect(subtitle).toHaveCSS("color", "rgb(92, 92, 92)")
|
||||
|
||||
@@ -174,6 +174,39 @@ const Group = HttpApiGroup.make("mock")
|
||||
success: Json,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("sessionPrompt", "/api/session/:sessionID/prompt", {
|
||||
params: SessionParams,
|
||||
payload: JsonPayload,
|
||||
success: Json,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("sessionSwitchAgent", "/api/session/:sessionID/agent", {
|
||||
params: SessionParams,
|
||||
payload: JsonPayload,
|
||||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("sessionSwitchModel", "/api/session/:sessionID/model", {
|
||||
params: SessionParams,
|
||||
payload: JsonPayload,
|
||||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.delete("sessionInboxCancel", "/api/session/:sessionID/inbox/:inboxID", {
|
||||
params: { ...SessionParams, inboxID: Schema.String },
|
||||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("sessionInboxSteer", "/api/session/:sessionID/inbox/:inboxID/steer", {
|
||||
params: { ...SessionParams, inboxID: Schema.String },
|
||||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.get("sessionPermission", "/api/session/:sessionID/permission", {
|
||||
params: SessionParams,
|
||||
|
||||
@@ -35,6 +35,9 @@ export interface MockServerConfig {
|
||||
fileContent?: (path: string) => unknown | Promise<unknown>
|
||||
findFiles?: (input: { query: string; dirs?: string; limit?: number }) => unknown
|
||||
sessionStatus?: Record<string, unknown> | (() => Record<string, unknown>)
|
||||
inbox?: unknown[] | (() => unknown[])
|
||||
onPrompt?: (input: { sessionID: string; body: Record<string, unknown> }) => void
|
||||
onInboxChange?: (input: { sessionID: string; inboxID: string; action: "cancel" | "steer" }) => void
|
||||
}
|
||||
|
||||
type MockStreamWindow = Window & {
|
||||
@@ -397,7 +400,39 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
|
||||
sessionFormReply: () => noContent,
|
||||
sessionFormCancel: () => noContent,
|
||||
sessionBackground: () => noContent,
|
||||
sessionInbox: () => Effect.succeed({ data: [] }),
|
||||
sessionInbox: () =>
|
||||
Effect.sync(() => ({ data: typeof config.inbox === "function" ? config.inbox() : (config.inbox ?? []) })),
|
||||
sessionPrompt: (ctx) =>
|
||||
Effect.sync(() => {
|
||||
const body = record(ctx.payload) ? ctx.payload : {}
|
||||
config.onPrompt?.({ sessionID: ctx.params.sessionID, body })
|
||||
return {
|
||||
data: {
|
||||
id: typeof body.id === "string" ? body.id : `inb_mock_${Date.now()}`,
|
||||
sessionID: ctx.params.sessionID,
|
||||
timeCreated: Date.now(),
|
||||
type: "user",
|
||||
payload: {
|
||||
text: typeof body.text === "string" ? body.text : "",
|
||||
...(body.files === undefined ? {} : { files: body.files }),
|
||||
...(body.agents === undefined ? {} : { agents: body.agents }),
|
||||
...(body.skills === undefined ? {} : { skills: body.skills }),
|
||||
...(body.metadata === undefined ? {} : { metadata: body.metadata }),
|
||||
},
|
||||
delivery: body.delivery === "queue" ? "queue" : "steer",
|
||||
},
|
||||
}
|
||||
}),
|
||||
sessionInboxCancel: (ctx) =>
|
||||
Effect.sync(() =>
|
||||
config.onInboxChange?.({ sessionID: ctx.params.sessionID, inboxID: ctx.params.inboxID, action: "cancel" }),
|
||||
).pipe(Effect.andThen(noContent)),
|
||||
sessionInboxSteer: (ctx) =>
|
||||
Effect.sync(() =>
|
||||
config.onInboxChange?.({ sessionID: ctx.params.sessionID, inboxID: ctx.params.inboxID, action: "steer" }),
|
||||
).pipe(Effect.andThen(noContent)),
|
||||
sessionSwitchAgent: () => noContent,
|
||||
sessionSwitchModel: () => noContent,
|
||||
sessionPermission: (ctx) => {
|
||||
const permissions =
|
||||
typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? [])
|
||||
|
||||
@@ -39,6 +39,26 @@ export type ComposerSelection = {
|
||||
variant?: string
|
||||
}
|
||||
|
||||
export type ComposerDelivery = "steer" | "queue"
|
||||
|
||||
// Contract between the composer and the session prompt queue. The session
|
||||
// owns the queue (pending inbox items); the composer only asks which delivery
|
||||
// a submit should use and delegates edit confirmation while a queued prompt
|
||||
// is loaded in the editor.
|
||||
export type ComposerQueue = {
|
||||
count: Accessor<number>
|
||||
// Delivery a plain submit uses right now.
|
||||
delivery: Accessor<ComposerDelivery>
|
||||
// Delivery offered on Mod+Enter and the toolbar hint button; undefined hides the hint.
|
||||
alternate: Accessor<ComposerDelivery | undefined>
|
||||
// Inbox ID of the queued prompt currently loaded in the composer for editing.
|
||||
editing: Accessor<string | undefined>
|
||||
confirmEdit: (delivery: ComposerDelivery) => void
|
||||
cancelEdit: () => void
|
||||
// Loads the first queued prompt into the composer. Returns false when the queue is empty.
|
||||
editFirst: () => boolean
|
||||
}
|
||||
|
||||
export type ComposerSession = {
|
||||
id: string
|
||||
directory: string
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||
import { ComposerEditor } from "./editor/editor"
|
||||
import { ModelSelectorPopover } from "@/providers/models/select-dialog"
|
||||
import { DialogSelectModelUnpaid } from "@/providers/models/unpaid"
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { formatKeybind, useCommand } from "@/shell/commands/command"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { ComposerModel } from "./model"
|
||||
|
||||
@@ -32,6 +32,7 @@ export function Composer(props: {
|
||||
modelControlsVisible={!props.model.model.loading}
|
||||
attachKeybind={command.keybindParts("file.attach")}
|
||||
attachShortcut={command.keybind("file.attach")}
|
||||
alternateKeybind={[formatKeybind("mod", language.t), formatKeybind("enter", language.t)]}
|
||||
modelControl={
|
||||
<ComposerModelControl
|
||||
loading={props.model.model.loading}
|
||||
|
||||
@@ -45,6 +45,7 @@ export type ComposerEditorProps = {
|
||||
modelControlsVisible?: boolean
|
||||
attachKeybind?: string[]
|
||||
attachShortcut?: string
|
||||
alternateKeybind?: string[]
|
||||
}
|
||||
|
||||
export function ComposerEditor(props: ComposerEditorProps) {
|
||||
@@ -177,10 +178,15 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (props.controller.onKeyDown(event)) return
|
||||
const mod = event.metaKey || event.ctrlKey
|
||||
if (mod && event.key === "ArrowUp" && !event.shiftKey && !event.altKey) {
|
||||
if (view.submit.queue?.editFirst()) event.preventDefault()
|
||||
return
|
||||
}
|
||||
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
||||
event.preventDefault()
|
||||
if (event.repeat) return
|
||||
props.controller.submit()
|
||||
props.controller.submit(mod ? { alternate: true } : undefined)
|
||||
}
|
||||
}}
|
||||
onKeyUp={updateCursor}
|
||||
@@ -248,6 +254,12 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={state.mode === "normal"}>
|
||||
<ComposerEditorAlternateDelivery
|
||||
controller={props.controller}
|
||||
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
|
||||
/>
|
||||
</Show>
|
||||
<ComposerEditorSubmitButton
|
||||
mode={state.mode}
|
||||
stopping={view.submit.stopping()}
|
||||
@@ -255,7 +267,7 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
accent={props.accentSubmit}
|
||||
sendLabel={i18n.t("ui.promptInput.send")}
|
||||
stopLabel={i18n.t("ui.promptInput.stop")}
|
||||
onSubmit={props.controller.submit}
|
||||
onSubmit={() => props.controller.submit()}
|
||||
onStop={props.controller.stop}
|
||||
/>
|
||||
</div>
|
||||
@@ -691,6 +703,42 @@ export function ComposerEditorPopover(props: {
|
||||
)
|
||||
}
|
||||
|
||||
// "Steer ⌘⏎" / "Queue ⌘⏎" hint next to the submit button: submits with the
|
||||
// delivery opposite to what plain Enter does. Visible only while the queue
|
||||
// exposes an alternate (turn running and composer holding a value), so it
|
||||
// disappears on its own when the current turn ends.
|
||||
function ComposerEditorAlternateDelivery(props: { controller: ComposerEditorModel; keybind: string[] }) {
|
||||
const i18n = useI18n()
|
||||
const view = props.controller.view
|
||||
const action = createMemo(() => {
|
||||
const queue = view.submit.queue
|
||||
if (!queue || !props.controller.canSubmit()) return undefined
|
||||
if (queue.editing()) return "steer" as const
|
||||
return queue.alternate()
|
||||
})
|
||||
return (
|
||||
<Show when={action()} keyed>
|
||||
{(delivery) => (
|
||||
<Tooltip placement="top" inactive={delivery !== "steer"} value={i18n.t("ui.promptInput.steerHint")}>
|
||||
<Button
|
||||
data-action="composer-alternate-delivery"
|
||||
type="button"
|
||||
variant="ghost-muted"
|
||||
size="small"
|
||||
class="me-3 gap-1.5 px-1.5 text-v2-text-text-muted ![font-weight:530]"
|
||||
onClick={() => props.controller.submit({ alternate: true })}
|
||||
>
|
||||
{delivery === "steer" ? i18n.t("ui.promptInput.steer") : i18n.t("ui.promptInput.queue")}
|
||||
<span class="hidden sm:block">
|
||||
<Keybind keys={props.keybind} variant="neutral" />
|
||||
</span>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
export function ComposerEditorSubmitButton(props: {
|
||||
mode: ComposerMode
|
||||
stopping: boolean
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type ComposerInteractionEvent,
|
||||
} from "../suggestions/machine"
|
||||
import { clonePrompt, promptLength } from "../prompt-parts"
|
||||
import type { ComposerQueue } from "../adapter"
|
||||
|
||||
export type ComposerSelectControl = {
|
||||
options: Accessor<ComposerOption[]>
|
||||
@@ -37,7 +38,8 @@ export type ComposerEditorView = {
|
||||
submit: {
|
||||
stopping: Accessor<boolean>
|
||||
working?: Accessor<boolean>
|
||||
onSubmit: () => void
|
||||
queue?: ComposerQueue
|
||||
onSubmit: (options?: { alternate?: boolean }) => void
|
||||
onStop: () => void
|
||||
}
|
||||
shell?: {
|
||||
@@ -212,6 +214,11 @@ export function createComposerEditor(input: {
|
||||
)
|
||||
}
|
||||
if (handled) return true
|
||||
if (event.key === "Escape" && input.view.submit.queue?.editing()) {
|
||||
event.preventDefault()
|
||||
input.view.submit.queue.cancelEdit()
|
||||
return true
|
||||
}
|
||||
const stop =
|
||||
input.view.submit.working?.() &&
|
||||
((event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "g") ||
|
||||
@@ -354,8 +361,8 @@ export function createComposerEditor(input: {
|
||||
openShell() {
|
||||
dispatch({ type: "mode.shell" })
|
||||
},
|
||||
submit() {
|
||||
input.view.submit.onSubmit()
|
||||
submit(options?: { alternate?: boolean }) {
|
||||
input.view.submit.onSubmit(options)
|
||||
dispatch({ type: "popover.close" })
|
||||
},
|
||||
stop() {
|
||||
|
||||
@@ -16,7 +16,7 @@ import { createSessionTabs } from "@/session/helpers"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { formatServerError } from "@/runtime/server/errors"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import type { ComposerAdapter, ComposerControls } from "./adapter"
|
||||
import type { ComposerAdapter, ComposerControls, ComposerQueue } from "./adapter"
|
||||
import type { ImageAttachmentPart } from "./state"
|
||||
import type { PromptHistoryComment } from "./history/entry"
|
||||
import { createComposerHistory } from "./history/store"
|
||||
@@ -27,7 +27,7 @@ export type ComposerModel = ComposerEditorModel & {
|
||||
readonly model: ComposerControls["model"]
|
||||
}
|
||||
|
||||
export function createComposerModel(adapter: ComposerAdapter): ComposerModel {
|
||||
export function createComposerModel(adapter: ComposerAdapter, options?: { queue?: ComposerQueue }): ComposerModel {
|
||||
const sdk = useWorkspaceLocation()
|
||||
const data = useData()
|
||||
const files = useFile()
|
||||
@@ -80,7 +80,11 @@ export function createComposerModel(adapter: ComposerAdapter): ComposerModel {
|
||||
})
|
||||
const stopping = createMemo(() => adapter.working() && blank())
|
||||
const placeholder = () =>
|
||||
composerPlaceholder(mode(), (key, params) => language.t(key as Parameters<typeof language.t>[0], params as never))
|
||||
composerPlaceholder(
|
||||
mode(),
|
||||
(key, params) => language.t(key as Parameters<typeof language.t>[0], params as never),
|
||||
adapter.working() || (options?.queue?.count() ?? 0) > 0,
|
||||
)
|
||||
|
||||
const historyComments = () => {
|
||||
const byID = new Map(comments.all().map((item) => [`${item.file}\n${item.id}`, item] as const))
|
||||
@@ -253,6 +257,11 @@ export function createComposerModel(adapter: ComposerAdapter): ComposerModel {
|
||||
resetHistory: () => controller.resetHistory(),
|
||||
setMode: (next) => controller.dispatch({ type: next === "shell" ? "mode.shell" : "mode.normal" }),
|
||||
closePopover: () => controller.dispatch({ type: "popover.close" }),
|
||||
delivery: (alternate) => {
|
||||
const queue = options?.queue
|
||||
if (!queue) return "steer"
|
||||
return (alternate ? queue.alternate() : queue.delivery()) ?? "steer"
|
||||
},
|
||||
notify: {
|
||||
missingSelection: () =>
|
||||
showToast({
|
||||
@@ -360,7 +369,18 @@ export function createComposerModel(adapter: ComposerAdapter): ComposerModel {
|
||||
submit: {
|
||||
stopping,
|
||||
working: adapter.working,
|
||||
onSubmit: () => void submission.submit(new Event("submit")),
|
||||
queue: options?.queue,
|
||||
onSubmit: (submitOptions) => {
|
||||
const queue = options?.queue
|
||||
// Confirming an edit re-admits the queued prompt instead of sending
|
||||
// the composer value as a new prompt. Enter keeps it queued in
|
||||
// place; the alternate action sends it as a steer.
|
||||
if (queue?.editing()) {
|
||||
queue.confirmEdit(submitOptions?.alternate ? "steer" : "queue")
|
||||
return
|
||||
}
|
||||
void submission.submit(new Event("submit"), submitOptions)
|
||||
},
|
||||
onStop: () => void submission.stop(),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -12,4 +12,12 @@ describe("Composer placeholder", () => {
|
||||
test("uses the command and context hint in normal mode", () => {
|
||||
expect(composerPlaceholder("normal", t)).toBe("ui.promptInput.placeholder.normal/@")
|
||||
})
|
||||
|
||||
test("uses the follow-up copy while a turn runs or prompts are queued", () => {
|
||||
expect(composerPlaceholder("normal", t, true)).toBe("ui.promptInput.placeholder.followUp/@")
|
||||
})
|
||||
|
||||
test("keeps the shell placeholder while a turn runs", () => {
|
||||
expect(composerPlaceholder("shell", t, true)).toBe("prompt.placeholder.shell:git status")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
export function composerPlaceholder(
|
||||
mode: "normal" | "shell",
|
||||
t: (key: string, params?: Record<string, string>) => string,
|
||||
followUp?: boolean,
|
||||
) {
|
||||
if (mode === "shell") return t("prompt.placeholder.shell", { example: "git status" })
|
||||
if (followUp) return t("ui.promptInput.placeholder.followUp", { slash: "/", at: "@" })
|
||||
return t("ui.promptInput.placeholder.normal", { slash: "/", at: "@" })
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Accessor } from "solid-js"
|
||||
import type { PromptHistoryComment } from "./history/entry"
|
||||
import type { ImageAttachmentPart, Prompt } from "./state"
|
||||
import { clonePrompt, promptLength } from "./prompt-parts"
|
||||
import type { ComposerAdapter, ComposerSelection, ComposerSession } from "./adapter"
|
||||
import type { ComposerAdapter, ComposerDelivery, ComposerSelection, ComposerSession } from "./adapter"
|
||||
import { createComposerSubmission } from "./submission-state"
|
||||
import { buildPromptRequest } from "./request"
|
||||
import { setCursorPosition } from "./editor/dom"
|
||||
@@ -21,7 +21,7 @@ type ComposerSubmission = {
|
||||
text: string
|
||||
images: ImageAttachmentPart[]
|
||||
selection: ComposerSelection
|
||||
delivery: "steer"
|
||||
delivery: ComposerDelivery
|
||||
}
|
||||
|
||||
type ComposerSubmitInput = {
|
||||
@@ -33,6 +33,7 @@ type ComposerSubmitInput = {
|
||||
resetHistory: () => void
|
||||
setMode: (mode: "normal" | "shell") => void
|
||||
closePopover: () => void
|
||||
delivery?: (alternate: boolean) => ComposerDelivery
|
||||
notify: {
|
||||
missingSelection: () => void
|
||||
failed: (kind: "shell" | "command" | "prompt", error: unknown) => void
|
||||
@@ -45,7 +46,7 @@ type ComposerSubmitInput = {
|
||||
}
|
||||
|
||||
export function createComposerSubmit(input: ComposerSubmitInput) {
|
||||
const submit = async (event: globalThis.Event) => {
|
||||
const submit = async (event: globalThis.Event, options?: { alternate?: boolean }) => {
|
||||
event.preventDefault()
|
||||
|
||||
const submission = createComposerSubmission({
|
||||
@@ -56,7 +57,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
||||
selection: item.selection ? { ...item.selection } : undefined,
|
||||
})),
|
||||
})
|
||||
const value = readSubmission(input, submission.prompt, submission.context)
|
||||
const value = readSubmission(input, submission.prompt, submission.context, options?.alternate ?? false)
|
||||
if (!value) {
|
||||
if (input.adapter.working() && input.adapter.kind === "active-session") void input.adapter.interrupt()
|
||||
return
|
||||
@@ -113,7 +114,10 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
||||
|
||||
if (command) {
|
||||
clearSubmission(input, submission)
|
||||
void sendCommand(session, value, command).catch((error) =>
|
||||
// Commands always steer: the server applies a command's configured
|
||||
// agent and model immediately at admission, so queueing one would
|
||||
// reconfigure the turn it is supposed to wait behind.
|
||||
void sendCommand(session, { ...value, delivery: "steer" }, command).catch((error) =>
|
||||
failSubmission(input, session, "command", error, restore, value.id),
|
||||
)
|
||||
return
|
||||
@@ -157,6 +161,7 @@ function readSubmission(
|
||||
input: ComposerSubmitInput,
|
||||
prompt: Prompt,
|
||||
context: ComposerSubmission["context"],
|
||||
alternate: boolean,
|
||||
): ComposerSubmission | undefined {
|
||||
const text = prompt.map((part) => ("content" in part ? part.content : "")).join("")
|
||||
const mode = input.mode()
|
||||
@@ -195,7 +200,7 @@ function readSubmission(
|
||||
model: { modelID: model.id, providerID: model.provider.id },
|
||||
variant,
|
||||
},
|
||||
delivery: "steer",
|
||||
delivery: input.delivery?.(alternate) ?? "steer",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,23 +290,30 @@ async function sendCommand(
|
||||
|
||||
async function sendPrompt(session: ComposerSession, value: ComposerSubmission) {
|
||||
const request = await buildSubmissionRequest(session, value)
|
||||
const current = session.current()
|
||||
if (current?.agent !== value.selection.agent) {
|
||||
await session.api.switchAgent({ sessionID: session.id, agent: value.selection.agent })
|
||||
}
|
||||
if (
|
||||
current?.model?.providerID !== value.selection.model.providerID ||
|
||||
current.model.id !== value.selection.model.modelID ||
|
||||
(current.model.variant ?? "default") !== (value.selection.variant ?? "default")
|
||||
) {
|
||||
await session.api.switchModel({
|
||||
sessionID: session.id,
|
||||
model: {
|
||||
id: value.selection.model.modelID,
|
||||
providerID: value.selection.model.providerID,
|
||||
variant: value.selection.variant,
|
||||
},
|
||||
})
|
||||
// Switching agent or model reconfigures the session immediately, and with it
|
||||
// the remainder of a running turn. A steer targets that turn, so its
|
||||
// selection applies now; a queued follow-up must not reconfigure the turn it
|
||||
// waits behind, so it runs with the session selection at delivery time (the
|
||||
// intended selection stays recorded in its metadata).
|
||||
if (value.delivery === "steer") {
|
||||
const current = session.current()
|
||||
if (current?.agent !== value.selection.agent) {
|
||||
await session.api.switchAgent({ sessionID: session.id, agent: value.selection.agent })
|
||||
}
|
||||
if (
|
||||
current?.model?.providerID !== value.selection.model.providerID ||
|
||||
current.model.id !== value.selection.model.modelID ||
|
||||
(current.model.variant ?? "default") !== (value.selection.variant ?? "default")
|
||||
) {
|
||||
await session.api.switchModel({
|
||||
sessionID: session.id,
|
||||
model: {
|
||||
id: value.selection.model.modelID,
|
||||
providerID: value.selection.model.providerID,
|
||||
variant: value.selection.variant,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const admission = {
|
||||
|
||||
@@ -677,6 +677,14 @@ export const dict = {
|
||||
"session.background.subagent.one": "{{count}} subagent",
|
||||
"session.background.subagent.other": "{{count}} subagents",
|
||||
"command.session.background": "Move to background",
|
||||
"session.queue.count.one": "{{count}} queued",
|
||||
"session.queue.count.other": "{{count}} queued",
|
||||
"session.queue.steer": "Steer",
|
||||
"session.queue.send": "Send",
|
||||
"session.queue.steerTooltip": "Send without interrupting",
|
||||
"session.queue.remove": "Remove",
|
||||
"session.queue.reorder": "Reorder queued prompt",
|
||||
"session.queue.attachments": "+ attachments",
|
||||
"session.timeline.notice.finished": "{{actor}} finished",
|
||||
"session.timeline.notice.failed": "{{actor}} failed",
|
||||
"session.timeline.notice.cancelled": "{{actor}} cancelled",
|
||||
@@ -961,6 +969,11 @@ export const dict = {
|
||||
"settings.general.row.showCustomAgents.title": "Show agent",
|
||||
"settings.general.row.showCustomAgents.description":
|
||||
"Switch between agents in the composer. When hidden, defaults to Build agent.",
|
||||
"settings.general.row.followUpBehavior.title": "Follow-up behavior",
|
||||
"settings.general.row.followUpBehavior.description":
|
||||
"Choose whether to queue follow-ups or steer the current turn. Use {{keybind}} to switch.",
|
||||
"settings.general.row.followUpBehavior.queue": "Queue",
|
||||
"settings.general.row.followUpBehavior.steer": "Steer",
|
||||
"settings.general.row.reasoningSummaries.title": "Show reasoning summaries",
|
||||
"settings.general.row.reasoningSummaries.description": "Display model reasoning summaries in the timeline",
|
||||
"settings.general.row.shellToolPartsExpanded.title": "Expand shell tool parts",
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { createMemo, For, Show } from "solid-js"
|
||||
import { DragDropProvider, PointerSensor } from "@dnd-kit/solid"
|
||||
import { isSortable, useSortable } from "@dnd-kit/solid/sortable"
|
||||
import { AutoScroller, Feedback, PointerActivationConstraints } from "@dnd-kit/dom"
|
||||
import { RestrictToVerticalAxis } from "@dnd-kit/abstract/modifiers"
|
||||
import { RestrictToElement } from "@dnd-kit/dom/modifiers"
|
||||
import { arrayMove } from "@dnd-kit/helpers"
|
||||
import { Button } from "@opencode-ai/ui/button"
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { SessionQueueView } from "./queue"
|
||||
|
||||
// Pullout above the composer listing the prompts queued behind the current
|
||||
// turn. The panel slides under the composer card (negative margin, opaque
|
||||
// composer background) so the two read as one attached surface.
|
||||
export function SessionQueuePanel(props: { queue: SessionQueueView }) {
|
||||
const language = useLanguage()
|
||||
const count = () => props.queue.rows().length
|
||||
let listRef!: HTMLDivElement
|
||||
return (
|
||||
<Show when={count() > 0}>
|
||||
<div
|
||||
data-component="session-queue-panel"
|
||||
class="relative z-0 -mb-3 rounded-xl bg-v2-background-bg-base px-1.5 pt-1.5 pb-[18px] shadow-[inset_0_0_0_0.5px_var(--v2-border-border-base)]"
|
||||
>
|
||||
<Show when={count() > 3}>
|
||||
<div class="px-1.5 pb-px text-[11px] font-[530] uppercase leading-[var(--line-height-tight)] tracking-[0.05px] text-v2-text-text-muted [font-variant-numeric:tabular-nums]">
|
||||
{language.plural("session.queue.count", count())}
|
||||
</div>
|
||||
</Show>
|
||||
<DragDropProvider
|
||||
sensors={(defaults) => [
|
||||
...defaults.filter((sensor) => sensor !== PointerSensor),
|
||||
PointerSensor.configure({
|
||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 4 })],
|
||||
}),
|
||||
]}
|
||||
modifiers={[RestrictToVerticalAxis, RestrictToElement.configure({ element: () => listRef })]}
|
||||
plugins={(defaults) => [
|
||||
...defaults.filter((plugin) => plugin !== AutoScroller && plugin !== Feedback),
|
||||
AutoScroller.configure({ acceleration: 8, threshold: { x: 0, y: 0.05 } }),
|
||||
Feedback.configure({ dropAnimation: null }),
|
||||
]}
|
||||
onDragEnd={(event) => {
|
||||
const source = event.operation.source
|
||||
if (event.canceled || !isSortable(source)) return
|
||||
if (source.initialIndex === source.index) return
|
||||
void props.queue.reorder(
|
||||
arrayMove(
|
||||
props.queue.rows().map((row) => row.id),
|
||||
source.initialIndex,
|
||||
source.index,
|
||||
),
|
||||
)
|
||||
}}
|
||||
>
|
||||
{/* Keyed on row IDs so store updates move row elements instead of
|
||||
remounting them, which would kill an in-flight drag. */}
|
||||
<div
|
||||
ref={listRef}
|
||||
class="flex flex-col gap-px"
|
||||
classList={{ "max-h-[131px] overflow-y-auto": count() > 3 }}
|
||||
>
|
||||
<For each={props.queue.rows().map((row) => row.id)}>
|
||||
{(id, index) => <SessionQueueRow queue={props.queue} id={id} index={index()} />}
|
||||
</For>
|
||||
</div>
|
||||
</DragDropProvider>
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: number }) {
|
||||
const language = useLanguage()
|
||||
const row = createMemo(() => props.queue.rows().find((entry) => entry.id === props.id))
|
||||
const editing = () => props.queue.editing() === props.id
|
||||
// While the turn is stopped the queue stays parked, so the first prompt
|
||||
// shows its actions without hover and its label reads Send: that is how a
|
||||
// parked queue resumes.
|
||||
const active = () => !props.queue.working() && props.index === 0
|
||||
const sortable = useSortable({
|
||||
get id() {
|
||||
return props.id
|
||||
},
|
||||
get index() {
|
||||
return props.index
|
||||
},
|
||||
get disabled() {
|
||||
return props.queue.busy()
|
||||
},
|
||||
})
|
||||
return (
|
||||
<Show when={row()} keyed>
|
||||
{(entry) => (
|
||||
<div
|
||||
ref={sortable.ref}
|
||||
data-component="session-queue-row"
|
||||
class="group/queue-row flex items-center justify-between gap-2 rounded-md py-1 ps-1 pe-2"
|
||||
classList={{
|
||||
"bg-v2-overlay-simple-overlay-hover": editing(),
|
||||
"opacity-60": sortable.isDragSource(),
|
||||
}}
|
||||
>
|
||||
<div class="flex min-w-0 flex-1 items-center gap-2">
|
||||
<button
|
||||
ref={sortable.handleRef}
|
||||
type="button"
|
||||
class="grid shrink-0 cursor-grab touch-none grid-cols-2 gap-x-[2px] gap-y-[2.25px] p-1"
|
||||
aria-label={language.t("session.queue.reorder")}
|
||||
>
|
||||
<For each={Array.from({ length: 6 })}>
|
||||
{() => <span class="size-[2px] bg-v2-background-bg-layer-04" />}
|
||||
</For>
|
||||
</button>
|
||||
<div class="flex min-w-0 flex-col">
|
||||
<button
|
||||
type="button"
|
||||
data-action="session-queue-edit"
|
||||
dir="auto"
|
||||
disabled={props.queue.busy()}
|
||||
class="max-w-full min-w-0 self-start truncate rounded-sm text-start text-[13px] font-[440] leading-[var(--line-height-compact)]"
|
||||
classList={{
|
||||
"text-v2-text-text-faint": editing(),
|
||||
"cursor-text text-v2-text-text-base hover:bg-v2-overlay-simple-overlay-hover": !editing(),
|
||||
}}
|
||||
onClick={() => props.queue.edit(props.id)}
|
||||
>
|
||||
{entry.text || (entry.attachments ? language.t("session.queue.attachments") : "")}
|
||||
</button>
|
||||
<Show when={entry.attachments && entry.text}>
|
||||
<span class="text-[13px] font-[440] leading-[var(--line-height-compact)] text-v2-text-text-muted">
|
||||
{language.t("session.queue.attachments")}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
data-slot="session-queue-actions"
|
||||
class="flex shrink-0 items-center gap-1.5"
|
||||
classList={{
|
||||
"opacity-0 focus-within:opacity-100 group-hover/queue-row:opacity-100 [@media(hover:none)]:opacity-100":
|
||||
!active() && !editing(),
|
||||
"pointer-events-none": props.queue.busy(),
|
||||
}}
|
||||
>
|
||||
<Show when={!editing()}>
|
||||
<Tooltip
|
||||
placement="top"
|
||||
inactive={!props.queue.working()}
|
||||
value={language.t("session.queue.steerTooltip")}
|
||||
>
|
||||
<Button
|
||||
data-action="session-queue-steer"
|
||||
type="button"
|
||||
size="small"
|
||||
variant="ghost-muted"
|
||||
icon="arrow-up"
|
||||
disabled={props.queue.busy()}
|
||||
class="text-v2-text-text-muted ![font-weight:530]"
|
||||
onClick={() => void props.queue.steer(props.id)}
|
||||
>
|
||||
{props.queue.working() ? language.t("session.queue.steer") : language.t("session.queue.send")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Show>
|
||||
<Tooltip placement="top" value={language.t("session.queue.remove")}>
|
||||
<IconButton
|
||||
data-action="session-queue-remove"
|
||||
type="button"
|
||||
size="small"
|
||||
variant="ghost-muted"
|
||||
icon={<Icon name="outline-xmark" />}
|
||||
disabled={props.queue.busy()}
|
||||
aria-label={language.t("session.queue.remove")}
|
||||
onClick={() => void props.queue.remove(props.id)}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { createEffect, createMemo, onCleanup, type Accessor } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import type { SessionInboxInfo } from "@opencode-ai/client/promise"
|
||||
import type { ComposerDelivery } from "@/composer/adapter"
|
||||
import type { ComposerModel } from "@/composer/model"
|
||||
import type { ComposerStateTarget } from "@/composer/submission-state"
|
||||
import type { ImageAttachmentPart, Prompt } from "@/composer/state"
|
||||
import { clonePrompt, promptLength } from "@/composer/prompt-parts"
|
||||
import { buildPromptRequest } from "@/composer/request"
|
||||
import { blobDataUrl } from "@/runtime/persistence/drafts"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
|
||||
export type QueuedPrompt = Extract<SessionInboxInfo, { type: "user" }>
|
||||
|
||||
type EditStash = {
|
||||
prompt: Prompt
|
||||
cursor: number
|
||||
mode: "normal" | "shell"
|
||||
retry: ReturnType<ComposerStateTarget["retry"]["current"]>
|
||||
}
|
||||
|
||||
export function createSessionQueue(input: {
|
||||
sessionID: string
|
||||
draft: ComposerStateTarget
|
||||
working: Accessor<boolean>
|
||||
behavior: Accessor<ComposerDelivery>
|
||||
composer: Accessor<ComposerModel | undefined>
|
||||
}) {
|
||||
const data = useData()
|
||||
const server = useServerSDK()
|
||||
const location = useWorkspaceLocation()
|
||||
const language = useLanguage()
|
||||
const [state, setState] = createStore<{ editing?: { id: string; stash: EditStash }; busy: boolean }>({ busy: false })
|
||||
|
||||
const queued = createMemo(() =>
|
||||
data.session.pending
|
||||
.list(input.sessionID)
|
||||
.filter((item): item is QueuedPrompt => item.type === "user" && item.delivery === "queue"),
|
||||
)
|
||||
const rows = createMemo(() =>
|
||||
queued().map((item) => ({
|
||||
id: item.id,
|
||||
text: queuedPromptText(item),
|
||||
attachments: (item.payload.files?.length ?? 0) > 0,
|
||||
})),
|
||||
)
|
||||
|
||||
createEffect(() => {
|
||||
const editing = state.editing
|
||||
if (!editing || state.busy || queued().some((item) => item.id === editing.id)) return
|
||||
setState("editing", undefined)
|
||||
})
|
||||
onCleanup(() => cancelEdit())
|
||||
|
||||
const notify = () => showToast({ title: language.t("common.requestFailed") })
|
||||
const run = (work: () => Promise<unknown>) => {
|
||||
setState("busy", true)
|
||||
return work()
|
||||
.catch(() => notify())
|
||||
.finally(async () => {
|
||||
await data.session.pending.sync(input.sessionID).catch(() => undefined)
|
||||
setState("busy", false)
|
||||
})
|
||||
}
|
||||
|
||||
const rewrite = async (inboxIDs: string[]) => {
|
||||
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
|
||||
if (pending.some((item) => item.delivery === "queue" && item.type !== "user"))
|
||||
throw new Error("Queued control items block reordering")
|
||||
const current = pending.filter((item): item is QueuedPrompt => item.type === "user" && item.delivery === "queue")
|
||||
const ordered = inboxIDs.flatMap((id) => current.filter((item) => item.id === id))
|
||||
if (ordered.length !== current.length) throw new Error("Queued prompts changed before reordering")
|
||||
const changed = ordered.findIndex((item, index) => item.id !== current[index]?.id)
|
||||
if (changed < 0) return
|
||||
|
||||
// Existing inbox APIs cannot reorder rows, so replace only the changed suffix.
|
||||
for (const item of ordered.slice(changed)) {
|
||||
await data.session.prompt({
|
||||
sessionID: input.sessionID,
|
||||
text: item.payload.text,
|
||||
files: item.payload.files?.map((file) => ({
|
||||
uri: `data:${file.mime};base64,${file.data}`,
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention,
|
||||
})),
|
||||
agents: item.payload.agents,
|
||||
skills: item.payload.skills,
|
||||
metadata: item.payload.metadata,
|
||||
delivery: "queue",
|
||||
resume: false,
|
||||
})
|
||||
}
|
||||
for (const item of current.slice(changed)) {
|
||||
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: item.id })
|
||||
}
|
||||
}
|
||||
const steer = (id: string) => {
|
||||
if (state.editing?.id === id) cancelEdit()
|
||||
return server.api.session.inbox.steer({ sessionID: input.sessionID, inboxID: id }).catch(() => notify())
|
||||
}
|
||||
const remove = (id: string) => {
|
||||
if (state.editing?.id === id) cancelEdit()
|
||||
return server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: id }).catch(() => notify())
|
||||
}
|
||||
const reorder = (inboxIDs: string[]) => {
|
||||
if (state.busy) return Promise.resolve()
|
||||
return run(() => rewrite(inboxIDs))
|
||||
}
|
||||
|
||||
const edit = (id: string) => {
|
||||
if (state.busy) return false
|
||||
if (state.editing?.id === id) return true
|
||||
const item = queued().find((entry) => entry.id === id)
|
||||
if (!item) return false
|
||||
if (state.editing) cancelEdit()
|
||||
const draft = input.draft.current()
|
||||
setState("editing", {
|
||||
id,
|
||||
stash: {
|
||||
prompt: clonePrompt(draft),
|
||||
cursor: input.draft.cursor() ?? promptLength(draft),
|
||||
mode: input.draft.mode.current(),
|
||||
retry: input.draft.retry.current(),
|
||||
},
|
||||
})
|
||||
const text = queuedPromptText(item)
|
||||
input.composer()?.dispatch({ type: "mode.normal" })
|
||||
input.draft.set([{ type: "text", content: text, start: 0, end: text.length }], text.length)
|
||||
input.composer()?.restoreFocus(text.length)
|
||||
return true
|
||||
}
|
||||
const cancelEdit = () => {
|
||||
const editing = state.editing
|
||||
if (!editing) return
|
||||
setState("editing", undefined)
|
||||
// Mode first, then prompt, then retry: mode and prompt writes both clear
|
||||
// the retry marker.
|
||||
input.composer()?.dispatch({ type: editing.stash.mode === "shell" ? "mode.shell" : "mode.normal" })
|
||||
input.draft.set(editing.stash.prompt, editing.stash.cursor)
|
||||
if (editing.stash.retry) input.draft.retry.set(editing.stash.retry)
|
||||
input.composer()?.restoreFocus(editing.stash.cursor)
|
||||
}
|
||||
const confirmEdit = (delivery: ComposerDelivery) => {
|
||||
const editing = state.editing
|
||||
if (!editing || state.busy) return
|
||||
const prompt = clonePrompt(input.draft.current())
|
||||
const text = prompt.map((part) => ("content" in part ? part.content : "")).join("")
|
||||
if (!text.trim() && !prompt.some((part) => part.type === "image")) return cancelEdit()
|
||||
const item = queued().find((entry) => entry.id === editing.id)
|
||||
const pristine = item && text.trim() === queuedPromptText(item) && !prompt.some((part) => part.type === "image")
|
||||
if (pristine && delivery === "queue") return cancelEdit()
|
||||
const inboxIDs = queued().map((entry) => entry.id)
|
||||
void run(async () => {
|
||||
const replacement = await editedPromptInput(input.sessionID, location().directory, item, prompt, text)
|
||||
// Admit before cancelling so a failed replacement never discards the original.
|
||||
const admitted = await data.session.prompt({
|
||||
...replacement,
|
||||
delivery,
|
||||
...(delivery === "queue" ? { resume: false } : {}),
|
||||
})
|
||||
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: editing.id })
|
||||
cancelEdit()
|
||||
if (delivery === "queue") await rewrite(inboxIDs.map((id) => (id === editing.id ? admitted.id : id)))
|
||||
})
|
||||
}
|
||||
const editFirst = () => {
|
||||
const first = queued()[0]
|
||||
if (!first) return false
|
||||
return edit(first.id)
|
||||
}
|
||||
|
||||
return {
|
||||
count: () => queued().length,
|
||||
delivery: () => (input.working() ? input.behavior() : "steer"),
|
||||
alternate: () => {
|
||||
if (state.editing) return "steer"
|
||||
if (!input.working()) return undefined
|
||||
return input.behavior() === "queue" ? "steer" : "queue"
|
||||
},
|
||||
editing: () => state.editing?.id,
|
||||
confirmEdit,
|
||||
cancelEdit,
|
||||
editFirst,
|
||||
rows,
|
||||
busy: () => state.busy,
|
||||
working: input.working,
|
||||
steer,
|
||||
remove,
|
||||
edit,
|
||||
reorder,
|
||||
}
|
||||
}
|
||||
|
||||
export type SessionQueue = ReturnType<typeof createSessionQueue>
|
||||
|
||||
// The slice of the queue the panel renders and drives.
|
||||
export type SessionQueueView = Pick<
|
||||
SessionQueue,
|
||||
"rows" | "editing" | "working" | "busy" | "steer" | "remove" | "edit" | "reorder"
|
||||
>
|
||||
|
||||
export function queuedPromptText(item: QueuedPrompt) {
|
||||
const display = item.payload.metadata?.["displayText"]
|
||||
return typeof display === "string" && display.length > 0 ? display : item.payload.text
|
||||
}
|
||||
|
||||
// Confirming an edit submits the current composer content as the replacement:
|
||||
// mentions and images added during the edit are parsed like a normal
|
||||
// submission, the original's stored attachments are preserved, and the
|
||||
// review-comment notes appended to the original's model-visible text survive.
|
||||
// Ambient composer context (open review comments) stays out: it belongs to
|
||||
// the next fresh prompt, not to a queued edit.
|
||||
async function editedPromptInput(
|
||||
sessionID: string,
|
||||
directory: string,
|
||||
item: QueuedPrompt | undefined,
|
||||
prompt: Prompt,
|
||||
text: string,
|
||||
) {
|
||||
const images = await Promise.all(
|
||||
prompt
|
||||
.filter((part): part is ImageAttachmentPart => part.type === "image")
|
||||
.map(async (part) => ({ ...part, dataUrl: await blobDataUrl(part.blob, part.mime) })),
|
||||
)
|
||||
const request = buildPromptRequest({ prompt, context: [], images, text, sessionDirectory: directory })
|
||||
const payload = item?.payload
|
||||
const display = item ? queuedPromptText(item) : ""
|
||||
const notes = payload && display && payload.text.startsWith(display) ? payload.text.slice(display.length) : ""
|
||||
const mention = (value: { start: number; end: number; text: string } | undefined) => {
|
||||
if (!value) return undefined
|
||||
const start = text.indexOf(value.text)
|
||||
if (start < 0) return undefined
|
||||
return { text: value.text, start, end: start + value.text.length }
|
||||
}
|
||||
// Structured mentions degrade to plain text in the editor, so an original
|
||||
// agent or skill reference survives the edit as long as its mention text
|
||||
// still appears; newly typed structured mentions come from the request.
|
||||
const agents = [
|
||||
...(payload?.agents?.filter(
|
||||
(agent) =>
|
||||
agent.mention &&
|
||||
text.includes(agent.mention.text) &&
|
||||
!request.agents.some((entry) => entry.name === agent.name),
|
||||
) ?? []),
|
||||
...request.agents,
|
||||
]
|
||||
const skills = [
|
||||
...(payload?.skills?.filter(
|
||||
(skill) =>
|
||||
skill.mention && text.includes(skill.mention.text) && !request.skills.some((entry) => entry.id === skill.id),
|
||||
) ?? []),
|
||||
...request.skills,
|
||||
]
|
||||
return {
|
||||
sessionID,
|
||||
text: request.text + notes,
|
||||
files: [
|
||||
...(payload?.files?.map((file) => ({
|
||||
uri: `data:${file.mime};base64,${file.data}`,
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: mention(file.mention),
|
||||
})) ?? []),
|
||||
...request.files.map((file) => ({ uri: file.uri, name: file.name, mention: file.mention })),
|
||||
],
|
||||
agents: agents.map((agent) => ({ name: agent.name, mention: mention(agent.mention) })),
|
||||
skills: skills.map((skill) => ({ id: skill.id, mention: mention(skill.mention) })),
|
||||
metadata: { ...payload?.metadata, displayText: request.displayText },
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { useNavigate } from "@solidjs/router"
|
||||
import { createEffect, on, onMount } from "solid-js"
|
||||
import { Composer } from "@/composer/composer"
|
||||
import { createComposerModel } from "@/composer/model"
|
||||
import { createComposerModel, type ComposerModel } from "@/composer/model"
|
||||
import { useComposerState } from "@/composer/persistence"
|
||||
import { createComposerControls } from "@/composer/selection"
|
||||
import { setCursorPosition } from "@/composer/editor/dom"
|
||||
@@ -27,8 +27,11 @@ import { createSessionRevert } from "../revert"
|
||||
import { SessionComposerRegion } from "./session-composer-region"
|
||||
import { createSessionComposerRegionController } from "./session-composer-region-controller"
|
||||
import { createActiveComposerAdapter } from "./adapter"
|
||||
import { createSessionQueue } from "./queue"
|
||||
import { SessionQueuePanel } from "./queue-panel"
|
||||
import { resolveSessionComposerSelection } from "./selection"
|
||||
import { createSessionRequestModel } from "../requests/model"
|
||||
import { useSettings } from "@/settings/model"
|
||||
|
||||
export function createActiveSessionRegion(input: {
|
||||
session: SessionModel
|
||||
@@ -216,6 +219,7 @@ export function ActiveSessionComposerRegion(props: {
|
||||
accentSubmit: boolean
|
||||
onResponseSubmit: () => void
|
||||
}) {
|
||||
const settings = useSettings()
|
||||
const region = createSessionComposerRegionController({
|
||||
state: props.model.region.state,
|
||||
parentID: props.session.data.parentID,
|
||||
@@ -231,11 +235,32 @@ export function ActiveSessionComposerRegion(props: {
|
||||
submitted: props.model.submitted,
|
||||
setEditor: props.model.input.setPromptRef,
|
||||
})
|
||||
const composer = createComposerModel(adapter)
|
||||
let composer: ComposerModel | undefined
|
||||
const queue = createSessionQueue({
|
||||
sessionID: requireSessionID(props.session),
|
||||
draft: adapter.state,
|
||||
working: adapter.working,
|
||||
behavior: settings.general.followUpBehavior,
|
||||
composer: () => composer,
|
||||
})
|
||||
composer = createComposerModel(adapter, { queue })
|
||||
return (
|
||||
<SessionComposerRegion
|
||||
controller={region}
|
||||
composer={<Composer model={composer} borderUnderlay accentSubmit={props.accentSubmit} />}
|
||||
composer={
|
||||
<div class="relative">
|
||||
<SessionQueuePanel queue={queue} />
|
||||
<div class="relative z-10">
|
||||
<Composer model={composer} borderUnderlay accentSubmit={props.accentSubmit} />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function requireSessionID(session: SessionModel) {
|
||||
const id = session.identity.params.id
|
||||
if (!id) throw new Error("Active Composer requires a Session ID")
|
||||
return id
|
||||
}
|
||||
|
||||
@@ -55,6 +55,28 @@ export function createSessionRevert(input: {
|
||||
await server.api.session.interrupt({ sessionID }).catch(() => undefined)
|
||||
}
|
||||
if (!(await request(() => server.api.session.revert.stage({ sessionID, messageID: message.id })))) return
|
||||
// Reverting to a previous prompt discards the pending queue (and pending
|
||||
// steers): they were written against the history being rewound. Cancel
|
||||
// the authoritative inbox merged with the local snapshot, fire-and-forget
|
||||
// so a slow request cannot delay restoring the composer. The cutoff keeps
|
||||
// the asynchronous sweep away from prompts admitted after the revert; an
|
||||
// old admission still in flight when the list is fetched can survive it,
|
||||
// and fully closing that race needs a server-side revert-discards-inbox
|
||||
// rule.
|
||||
const cutoff = Date.now()
|
||||
const local = data.session.pending
|
||||
.list(sessionID)
|
||||
.filter((item) => item.type === "user")
|
||||
.map((item) => item.id)
|
||||
void server.api.session.inbox
|
||||
.list({ sessionID })
|
||||
.then((rows) => rows.filter((row) => row.type === "user" && row.timeCreated <= cutoff).map((row) => row.id))
|
||||
.catch(() => [])
|
||||
.then((authoritative) => {
|
||||
new Set([...local, ...authoritative]).forEach(
|
||||
(inboxID) => void server.api.session.inbox.cancel({ sessionID, inboxID }).catch(() => undefined),
|
||||
)
|
||||
})
|
||||
restore(target, message)
|
||||
owner.run(() => input.setActiveMessage(previous))
|
||||
}
|
||||
|
||||
@@ -7,7 +7,13 @@ import { TextInput } from "@opencode-ai/ui/text-input"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useUpdaterAction } from "@/shell/updates/action"
|
||||
import { type TerminalPlacement, type WorkspaceDefaultDestination, useSettings } from "@/settings/model"
|
||||
import {
|
||||
type FollowUpBehavior,
|
||||
type TerminalPlacement,
|
||||
type WorkspaceDefaultDestination,
|
||||
useSettings,
|
||||
} from "@/settings/model"
|
||||
import { formatKeybind } from "@/shell/commands/command"
|
||||
import { ExternalLink } from "@/runtime/platform/external-link"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import { SettingsRow } from "@/settings/row"
|
||||
@@ -148,6 +154,35 @@ const TerminalPlacementSetting: Component = () => {
|
||||
)
|
||||
}
|
||||
|
||||
const FollowUpBehaviorSetting: Component = () => {
|
||||
const language = useLanguage()
|
||||
const settings = useSettings()
|
||||
const options = createMemo((): { value: FollowUpBehavior; label: string }[] => [
|
||||
{ value: "queue", label: language.t("settings.general.row.followUpBehavior.queue") },
|
||||
{ value: "steer", label: language.t("settings.general.row.followUpBehavior.steer") },
|
||||
])
|
||||
|
||||
return (
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.followUpBehavior.title")}
|
||||
description={language.t("settings.general.row.followUpBehavior.description", {
|
||||
keybind: formatKeybind("mod+enter", language.t),
|
||||
})}
|
||||
>
|
||||
<Select
|
||||
data-action="settings-follow-up-behavior"
|
||||
options={options()}
|
||||
current={options().find((option) => option.value === settings.general.followUpBehavior())}
|
||||
value={(option) => option.value}
|
||||
label={(option) => option.label}
|
||||
placement="bottom-end"
|
||||
gutter={6}
|
||||
onSelect={(option) => option && settings.general.setFollowUpBehavior(option.value)}
|
||||
/>
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
|
||||
const AppearanceSection: Component<{ controller: AppearanceSettingsController }> = (props) => {
|
||||
const language = useLanguage()
|
||||
return (
|
||||
@@ -294,6 +329,7 @@ export const SettingsGeneral: Component<{
|
||||
|
||||
<ShellSetting controller={shell} />
|
||||
<TerminalPlacementSetting />
|
||||
<FollowUpBehaviorSetting />
|
||||
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.reasoningSummaries.title")}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { monoDefault, monoFontFamily, sansDefault, sansFontFamily, terminalFontFamily } from "./model"
|
||||
|
||||
describe("settings font families", () => {
|
||||
test("defaults normal text to Inter", () => {
|
||||
expect(sansDefault).toBe("Inter")
|
||||
expect(sansFontFamily(undefined)).toStartWith('"Inter", ')
|
||||
expect(sansFontFamily("")).toStartWith('"Inter", ')
|
||||
expect(sansFontFamily(" ")).toStartWith('"Inter", ')
|
||||
})
|
||||
|
||||
test("keeps custom normal fonts ahead of the default", () => {
|
||||
expect(sansFontFamily("Custom Sans")).toStartWith('"Custom Sans", "Inter", ')
|
||||
})
|
||||
|
||||
test("defaults monospace text to IBM Plex Mono", () => {
|
||||
expect(monoDefault).toBe("IBM Plex Mono")
|
||||
expect(monoFontFamily(undefined)).toStartWith('"IBM Plex Mono", ')
|
||||
expect(monoFontFamily("")).toStartWith('"IBM Plex Mono", ')
|
||||
expect(monoFontFamily(" ")).toStartWith('"IBM Plex Mono", ')
|
||||
})
|
||||
|
||||
test("keeps custom monospace fonts ahead of the default", () => {
|
||||
expect(monoFontFamily("Custom Mono")).toStartWith('"Custom Mono", "IBM Plex Mono", ')
|
||||
})
|
||||
|
||||
test("preserves the separate terminal font default", () => {
|
||||
expect(terminalFontFamily(undefined)).toStartWith('"JetBrainsMono Nerd Font Mono", ')
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import { ScopedKey, type ServerScope } from "@/runtime/server/scope"
|
||||
export type WorkspaceDefaultDestination = "last-used" | "local" | "new"
|
||||
export type WorkspaceLastUsed = "local" | "workspace"
|
||||
export type TerminalPlacement = "side" | "bottom"
|
||||
export type FollowUpBehavior = "queue" | "steer"
|
||||
|
||||
export interface NotificationSettings {
|
||||
agent: boolean
|
||||
@@ -39,6 +40,7 @@ export interface Settings {
|
||||
showCustomAgents: boolean
|
||||
mobileTitlebarPosition: "top" | "bottom"
|
||||
terminalPlacement: TerminalPlacement
|
||||
followUpBehavior: FollowUpBehavior
|
||||
}
|
||||
appearance: {
|
||||
fontSize: number
|
||||
@@ -58,12 +60,12 @@ export interface Settings {
|
||||
sounds: SoundSettings
|
||||
}
|
||||
|
||||
export const monoDefault = "System Mono"
|
||||
export const sansDefault = "System Sans"
|
||||
export const monoDefault = "IBM Plex Mono"
|
||||
export const sansDefault = "Inter"
|
||||
export const terminalDefault = "JetBrainsMono Nerd Font Mono"
|
||||
const monoFallback =
|
||||
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
|
||||
const sansFallback = 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
|
||||
'"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
|
||||
const sansFallback = '"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
|
||||
const terminalFallback =
|
||||
'"JetBrainsMono Nerd Font Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
|
||||
|
||||
@@ -126,6 +128,7 @@ const defaultSettings: Settings = {
|
||||
showCustomAgents: false,
|
||||
mobileTitlebarPosition: "top",
|
||||
terminalPlacement: "side",
|
||||
followUpBehavior: "steer",
|
||||
},
|
||||
appearance: {
|
||||
fontSize: 14,
|
||||
@@ -256,6 +259,10 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
||||
setTerminalPlacement(value: TerminalPlacement) {
|
||||
setStore("general", "terminalPlacement", value)
|
||||
},
|
||||
followUpBehavior: withFallback(() => store.general?.followUpBehavior, defaultSettings.general.followUpBehavior),
|
||||
setFollowUpBehavior(value: FollowUpBehavior) {
|
||||
setStore("general", "followUpBehavior", value)
|
||||
},
|
||||
},
|
||||
visibility: {
|
||||
fileTree: showFileTree,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export type Policy = boolean | "notify"
|
||||
export type Action = "none" | "upgrade"
|
||||
export type Action = "none" | "notify" | "upgrade"
|
||||
|
||||
const maximumComponent = "9007199254740991"
|
||||
const versionPattern =
|
||||
@@ -12,7 +12,7 @@ export function action(current: string, latest: string, policy: Policy): Action
|
||||
if (!currentVersion || !latestVersion || sameRelease(currentVersion, latestVersion)) return "none"
|
||||
// Major upgrades are never installed automatically.
|
||||
if (currentVersion.major !== latestVersion.major) return "none"
|
||||
return "upgrade"
|
||||
return policy === "notify" ? "notify" : "upgrade"
|
||||
}
|
||||
|
||||
function parseReleaseVersion(input: string) {
|
||||
|
||||
@@ -12,8 +12,12 @@ describe("updater", () => {
|
||||
test("automatically updates patches and minors", () => {
|
||||
expect(action("1.2.3", "1.2.4", true)).toBe("upgrade")
|
||||
expect(action("1.2.3", "1.3.0", true)).toBe("upgrade")
|
||||
expect(action("1.2.3", "1.2.4", "notify")).toBe("upgrade")
|
||||
expect(action("1.2.3", "1.3.0", "notify")).toBe("upgrade")
|
||||
})
|
||||
|
||||
test("reports patches and minors without automatically installing them", () => {
|
||||
expect(action("1.2.3", "1.2.4", "notify")).toBe("notify")
|
||||
expect(action("1.2.3", "1.3.0", "notify")).toBe("notify")
|
||||
expect(action("1.2.3", "1.2.3", "notify")).toBe("none")
|
||||
})
|
||||
|
||||
test("skips when autoupdate is disabled", () => {
|
||||
|
||||
@@ -162,6 +162,8 @@ export const layer = Layer.effect(
|
||||
})
|
||||
const next = action(OPENCODE_VERSION, version, policy)
|
||||
if (next === "none") return yield* Effect.logInfo("update check done", { action: "up-to-date" })
|
||||
if (next === "notify")
|
||||
return yield* Effect.logInfo("OpenCode update available", { current: OPENCODE_VERSION, latest: version })
|
||||
const detected = yield* method()
|
||||
if (!detected) return yield* Effect.logWarning("automatic update skipped: installation method not found")
|
||||
yield* upgrade(detected, version)
|
||||
|
||||
@@ -237,9 +237,8 @@ export default function PrivacyPolicy() {
|
||||
</td>
|
||||
<td>
|
||||
<ul>
|
||||
<li>Providing, Customizing and Improving the Services</li>
|
||||
<li>Marketing the Services</li>
|
||||
<li>Corresponding with You</li>
|
||||
<li>Passing through to upstream provider to provide services</li>
|
||||
<li>Not stored</li>
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
import type { ToolDefinition } from "@opencode-ai/ai"
|
||||
import { Tool } from "@opencode-ai/schema/tool"
|
||||
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec"
|
||||
import { Effect, JsonSchema, Schema } from "effect"
|
||||
import { Cache, Effect, JsonSchema, Schema, SchemaIssue, SchemaRepresentation } from "effect"
|
||||
|
||||
const formatEffectIssues = SchemaIssue.makeFormatterStandardSchemaV1()
|
||||
|
||||
const jsonSchemas = Effect.runSync(
|
||||
Cache.make<JsonSchema.JsonSchema, Schema.Codec<unknown> | undefined>({
|
||||
capacity: 100,
|
||||
lookup: (schema) =>
|
||||
Effect.try({
|
||||
try: () => jsonSchema(schema),
|
||||
catch: () => undefined,
|
||||
}).pipe(Effect.orElseSucceed(() => undefined)),
|
||||
}),
|
||||
)
|
||||
|
||||
export const definition = (tool: Tool.Info<any, any>): ToolDefinition => ({
|
||||
name: effectiveName(tool),
|
||||
@@ -12,7 +25,7 @@ export const definition = (tool: Tool.Info<any, any>): ToolDefinition => ({
|
||||
|
||||
export const execute = (tool: Tool.Info<any, any>, input: unknown, context: Tool.Context) =>
|
||||
Effect.gen(function* () {
|
||||
const decoded = yield* decodeInput(tool.input, input)
|
||||
const decoded = yield* decodeInput(tool, input)
|
||||
// Tool implementations declare `Tool.Error` but plugins can fail with anything at
|
||||
// runtime. A foreign typed failure would slip past every `catchTag("Tool.Error")`
|
||||
// downstream and leave its call permanently unsettled, so the declared contract is
|
||||
@@ -44,13 +57,51 @@ export const execute = (tool: Tool.Info<any, any>, input: unknown, context: Tool
|
||||
}
|
||||
})
|
||||
|
||||
const decodeInput = (schema: Tool.ValueSchema<any>, value: unknown) => {
|
||||
if (Schema.isSchema(schema))
|
||||
return Schema.decodeUnknownEffect(schema)(value).pipe(
|
||||
Effect.mapError((error) => new Tool.Error({ message: `Invalid tool input: ${error.message}` })),
|
||||
const decodeInput = (tool: Tool.Info<any, any>, value: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* validateInput(tool.input, value)
|
||||
if (result.issues)
|
||||
return yield* new Tool.Error({ message: formatInputIssues(effectiveName(tool), result.issues, value) })
|
||||
return result.value
|
||||
})
|
||||
|
||||
const validateInput = (
|
||||
schema: Tool.ValueSchema<any>,
|
||||
value: unknown,
|
||||
): Effect.Effect<StandardSchemaV1.Result<unknown>> => {
|
||||
if (isStandardSchema(schema)) return validateStandard(schema, value)
|
||||
return Effect.gen(function* () {
|
||||
const codec = Schema.isSchema(schema) ? schema : yield* Cache.get(jsonSchemas, schema)
|
||||
if (codec === undefined) return { value }
|
||||
return yield* Schema.decodeUnknownEffect(codec)(value, { errors: "all" }).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => formatEffectIssues(error.issue),
|
||||
onSuccess: (value) => ({ value }),
|
||||
}),
|
||||
)
|
||||
if (isStandardSchema(schema)) return validateStandard(schema, value, "Invalid tool input")
|
||||
return Effect.succeed(value)
|
||||
})
|
||||
}
|
||||
|
||||
const formatInputIssues = (tool: string, issues: ReadonlyArray<StandardSchemaV1.Issue>, value: unknown) => {
|
||||
const details = issues.slice(0, 5).map((issue) => {
|
||||
const path =
|
||||
issue.path?.reduce<string>((path, segment) => {
|
||||
const key = typeof segment === "object" ? segment.key : segment
|
||||
if (typeof key === "number") return `${path}[${key}]`
|
||||
return path === "" ? String(key) : `${path}.${String(key)}`
|
||||
}, "") || "root"
|
||||
return `- ${path}: ${issue.message}`
|
||||
})
|
||||
if (issues.length > 5) details.push(`- ...and ${issues.length - 5} more ${issues.length === 6 ? "issue" : "issues"}`)
|
||||
return `Invalid arguments for tool "${tool}":\n${details.join("\n")}\n\nArguments provided:\n${JSON.stringify(value, null, 2)}\n\nUpdate the arguments and call the tool again.`
|
||||
}
|
||||
|
||||
const jsonSchema = (schema: JsonSchema.JsonSchema) => {
|
||||
const draft =
|
||||
(typeof schema.$schema === "string" && schema.$schema.includes("draft-07")) || "definitions" in schema
|
||||
? JsonSchema.fromSchemaDraft07(schema)
|
||||
: JsonSchema.fromSchemaDraft2020_12(schema)
|
||||
return Schema.make<Schema.Codec<unknown>>(SchemaRepresentation.fromJsonSchemaDocument(draft).ast)
|
||||
}
|
||||
|
||||
const encodeOutput = (schema: Tool.ValueSchema<any>, value: unknown) => {
|
||||
@@ -62,7 +113,15 @@ const encodeOutput = (schema: Tool.ValueSchema<any>, value: unknown) => {
|
||||
),
|
||||
)
|
||||
if (isStandardSchema(schema))
|
||||
return validateStandard(schema, value, "Tool returned an invalid value for its output schema")
|
||||
return validateStandard(schema, value).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.issues
|
||||
? new Tool.Error({
|
||||
message: `Tool returned an invalid value for its output schema: ${result.issues.map((issue) => issue.message).join(", ")}`,
|
||||
})
|
||||
: Effect.succeed(result.value),
|
||||
),
|
||||
)
|
||||
return Schema.decodeUnknownEffect(Schema.Json)(value).pipe(
|
||||
Effect.mapError(
|
||||
(error) => new Tool.Error({ message: `Tool returned a non-JSON value for its output schema: ${error.message}` }),
|
||||
@@ -78,26 +137,16 @@ const isStandardSchema = (
|
||||
const validateStandard = (
|
||||
schema: StandardSchemaV1<any, any> & StandardJSONSchemaV1<any, any>,
|
||||
value: unknown,
|
||||
prefix: string,
|
||||
) =>
|
||||
): Effect.Effect<StandardSchemaV1.Result<unknown>> =>
|
||||
Effect.gen(function* () {
|
||||
const pending = yield* Effect.try({
|
||||
try: () => schema["~standard"].validate(value),
|
||||
catch: (error) => standardFailure(prefix, error),
|
||||
})
|
||||
const result =
|
||||
pending instanceof Promise
|
||||
? yield* Effect.tryPromise({ try: () => pending, catch: (error) => standardFailure(prefix, error) })
|
||||
: pending
|
||||
if (result.issues)
|
||||
return yield* new Tool.Error({
|
||||
message: `${prefix}: ${result.issues.map((issue) => issue.message).join(", ")}`,
|
||||
})
|
||||
return result.value
|
||||
})
|
||||
|
||||
const standardFailure = (prefix: string, error: unknown) =>
|
||||
new Tool.Error({ message: `${prefix}: ${error instanceof Error ? error.message : String(error)}` })
|
||||
const result = yield* Effect.try({ try: () => schema["~standard"].validate(value), catch: (error) => error })
|
||||
return result instanceof Promise ? yield* Effect.tryPromise({ try: () => result, catch: (error) => error }) : result
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ issues: [{ message: error instanceof Error ? error.message : String(error) }] }),
|
||||
onSuccess: (result) => result,
|
||||
}),
|
||||
)
|
||||
|
||||
const inputJsonSchema = (schema: Tool.ValueSchema<any>): JsonSchema.JsonSchema => {
|
||||
if (schema === undefined || schema === null) return {}
|
||||
|
||||
@@ -511,7 +511,11 @@ describe("Tool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
error: { type: "tool.execution", message: expect.stringContaining("Invalid tool input") },
|
||||
error: {
|
||||
type: "tool.execution",
|
||||
message:
|
||||
'Invalid arguments for tool "transformed":\n- value: Expected boolean\n\nArguments provided:\n{\n "value": "yes"\n}\n\nUpdate the arguments and call the tool again.',
|
||||
},
|
||||
})
|
||||
expect(executed).toEqual(["yes"])
|
||||
|
||||
|
||||
@@ -100,7 +100,11 @@ describe("QuestionTool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
error: { type: "tool.execution", message: expect.stringContaining("Invalid tool input") },
|
||||
error: {
|
||||
type: "tool.execution",
|
||||
message:
|
||||
'Invalid arguments for tool "question":\n- questions: Expected a value with a length of at least 1\n\nArguments provided:\n{\n "questions": []\n}\n\nUpdate the arguments and call the tool again.',
|
||||
},
|
||||
})
|
||||
expect(capturedInput()).toBeUndefined()
|
||||
}),
|
||||
|
||||
@@ -144,7 +144,12 @@ test("portable schema failures become tool failures", async () => {
|
||||
"~standard": {
|
||||
version: 1,
|
||||
vendor: "test",
|
||||
validate: (_value: unknown) => ({ issues: [{ message: "expected a string" }] }),
|
||||
validate: (_value: unknown) => ({
|
||||
issues: [
|
||||
{ path: ["value"], message: "expected a string" },
|
||||
{ path: [{ key: "nested" }, { key: "count" }], message: "expected a positive integer" },
|
||||
],
|
||||
}),
|
||||
jsonSchema: {
|
||||
input: () => ({ type: "string" }),
|
||||
output: () => ({ type: "string" }),
|
||||
@@ -152,19 +157,76 @@ test("portable schema failures become tool failures", async () => {
|
||||
},
|
||||
}
|
||||
|
||||
const error = await Effect.runPromiseExit(
|
||||
execute(
|
||||
{
|
||||
name: "invalid",
|
||||
description: "Invalid",
|
||||
input,
|
||||
execute: () => Effect.succeed({ content: "unused" }),
|
||||
},
|
||||
1,
|
||||
{} as Tool.Context,
|
||||
const error = await Effect.runPromise(
|
||||
Effect.flip(
|
||||
execute(
|
||||
{
|
||||
name: "invalid",
|
||||
description: "Invalid",
|
||||
input,
|
||||
execute: () => Effect.succeed({ content: "unused" }),
|
||||
},
|
||||
1,
|
||||
{} as Tool.Context,
|
||||
),
|
||||
),
|
||||
)
|
||||
expect(error.toString()).toContain("Invalid tool input: expected a string")
|
||||
expect(error).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "invalid":\n- value: expected a string\n- nested.count: expected a positive integer\n\nArguments provided:\n1\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("Effect schema failures use normalized input issues", async () => {
|
||||
const tool: Info = {
|
||||
name: "effect",
|
||||
description: "Effect tool",
|
||||
input: Schema.Struct({
|
||||
value: Schema.String,
|
||||
nested: Schema.Struct({ count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)) }),
|
||||
}),
|
||||
execute: () => Effect.succeed({ content: "unused" }),
|
||||
}
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(Effect.flip(execute(tool, { value: 1, nested: { count: 0 } }, {} as Tool.Context))),
|
||||
).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "effect":\n- value: Expected string\n- nested.count: Expected a value greater than or equal to 1\n\nArguments provided:\n{\n "value": 1,\n "nested": {\n "count": 0\n }\n}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("input error prompts limit normalized issues", async () => {
|
||||
const input = {
|
||||
"~standard": {
|
||||
version: 1,
|
||||
vendor: "test",
|
||||
validate: (_value: unknown) => ({
|
||||
issues: Array.from({ length: 6 }, (_, index) => ({ message: `issue ${index + 1}` })),
|
||||
}),
|
||||
jsonSchema: {
|
||||
input: () => ({}),
|
||||
output: () => ({}),
|
||||
},
|
||||
},
|
||||
}
|
||||
const tool: Info = {
|
||||
name: "limited",
|
||||
description: "Limited issues",
|
||||
input,
|
||||
execute: () => Effect.succeed({ content: "unused" }),
|
||||
}
|
||||
|
||||
expect(await Effect.runPromise(Effect.flip(execute(tool, {}, {} as Tool.Context)))).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "limited":\n- root: issue 1\n- root: issue 2\n- root: issue 3\n- root: issue 4\n- root: issue 5\n- ...and 1 more issue\n\nArguments provided:\n{}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("canonical results carry metadata with typed output", async () => {
|
||||
@@ -185,8 +247,21 @@ test("canonical results carry metadata with typed output", async () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("raw JSON schemas are render-only and omitted output means model-only", async () => {
|
||||
const input = { type: "object", properties: { value: { type: "string" } } }
|
||||
test("raw JSON schemas validate and decode tool input", async () => {
|
||||
const input = {
|
||||
type: "object",
|
||||
properties: {
|
||||
value: { type: "string" },
|
||||
nested: {
|
||||
type: "object",
|
||||
properties: { count: { type: "integer", minimum: 1 } },
|
||||
required: ["count"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
required: ["value"],
|
||||
additionalProperties: false,
|
||||
}
|
||||
const tool: Info = {
|
||||
name: "raw",
|
||||
description: "Raw tool",
|
||||
@@ -197,11 +272,79 @@ test("raw JSON schemas are render-only and omitted output means model-only", asy
|
||||
expect(definition(tool)).toEqual({
|
||||
name: "raw",
|
||||
description: "Raw tool",
|
||||
inputSchema: { type: "object", properties: { value: { type: "string" } } },
|
||||
inputSchema: input,
|
||||
})
|
||||
expect(await Effect.runPromise(execute(tool, { value: 1 }, {} as Tool.Context))).toEqual({
|
||||
expect(await Effect.runPromise(execute(tool, { value: "ok", extra: true }, {} as Tool.Context))).toEqual({
|
||||
output: undefined,
|
||||
content: [{ type: "text", text: '{"value":1}' }],
|
||||
content: [{ type: "text", text: '{"value":"ok"}' }],
|
||||
})
|
||||
expect(await Effect.runPromise(Effect.flip(execute(tool, { value: 1 }, {} as Tool.Context)))).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "raw":\n- value: Expected string\n\nArguments provided:\n{\n "value": 1\n}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
expect(await Effect.runPromise(Effect.flip(execute(tool, {}, {} as Tool.Context)))).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "raw":\n- value: Missing key\n\nArguments provided:\n{}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
expect(
|
||||
await Effect.runPromise(Effect.flip(execute(tool, { value: "ok", nested: { count: 0 } }, {} as Tool.Context))),
|
||||
).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "raw":\n- nested.count: Expected a value greater than or equal to 1\n\nArguments provided:\n{\n "value": "ok",\n "nested": {\n "count": 0\n }\n}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
expect(
|
||||
await Effect.runPromise(Effect.flip(execute(tool, { value: 1, nested: { count: 0 } }, {} as Tool.Context))),
|
||||
).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "raw":\n- value: Expected string\n- nested.count: Expected a value greater than or equal to 1\n\nArguments provided:\n{\n "value": 1,\n "nested": {\n "count": 0\n }\n}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("raw JSON schemas resolve draft-07 definitions", async () => {
|
||||
const tool: Info = {
|
||||
name: "draft-07",
|
||||
description: "Draft-07 tool",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: { value: { $ref: "#/definitions/value" } },
|
||||
required: ["value"],
|
||||
definitions: { value: { type: "string" } },
|
||||
},
|
||||
execute: (input) => Effect.succeed({ content: JSON.stringify(input) }),
|
||||
}
|
||||
|
||||
expect(await Effect.runPromise(execute(tool, { value: "ok" }, {} as Tool.Context))).toMatchObject({
|
||||
content: [{ type: "text", text: '{"value":"ok"}' }],
|
||||
})
|
||||
expect(await Effect.runPromise(Effect.flip(execute(tool, { value: 1 }, {} as Tool.Context)))).toEqual(
|
||||
new Tool.Error({
|
||||
message:
|
||||
'Invalid arguments for tool "draft-07":\n- value: Expected value\n\nArguments provided:\n{\n "value": 1\n}\n\nUpdate the arguments and call the tool again.',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("raw JSON schemas pass input through when they cannot be imported", async () => {
|
||||
const tool: Info = {
|
||||
name: "invalid-schema",
|
||||
description: "Invalid schema tool",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: { value: { $ref: "#/$defs/missing" } },
|
||||
},
|
||||
execute: (input) => Effect.succeed({ content: JSON.stringify(input) }),
|
||||
}
|
||||
|
||||
expect(await Effect.runPromise(execute(tool, { value: 1, extra: true }, {} as Tool.Context))).toMatchObject({
|
||||
content: [{ type: "text", text: '{"value":1,"extra":true}' }],
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -118,7 +118,8 @@ describe("search tools", () => {
|
||||
status: "error",
|
||||
error: {
|
||||
type: "tool.execution",
|
||||
message: 'Invalid tool input: Pattern must not be empty\n at ["pattern"]',
|
||||
message:
|
||||
'Invalid arguments for tool "grep":\n- pattern: Pattern must not be empty\n\nArguments provided:\n{\n "pattern": ""\n}\n\nUpdate the arguments and call the tool again.',
|
||||
},
|
||||
})
|
||||
}),
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import { Plugin, PluginContextProvider, usePlugin } from "@opencode-ai/plugin/tui"
|
||||
import { ensureRuntimePluginSupport } from "@opentui/solid/runtime-plugin-support/configure"
|
||||
|
||||
ensureRuntimePluginSupport()
|
||||
ensureRuntimePluginSupport({
|
||||
additional: {
|
||||
"@opencode-ai/plugin/tui": { Plugin, PluginContextProvider, usePlugin },
|
||||
},
|
||||
})
|
||||
|
||||
@@ -131,6 +131,7 @@ const source = {
|
||||
"ui.promptInput.label": "Prompt",
|
||||
"ui.promptInput.placeholder.shell": "Enter shell command...",
|
||||
"ui.promptInput.placeholder.normal": "Ask anything, {{slash}} for commands, {{at}} for context...",
|
||||
"ui.promptInput.placeholder.followUp": "Add follow-up, {{slash}} for commands, {{at}} for context...",
|
||||
"ui.promptInput.add": "Add images and files",
|
||||
"ui.promptInput.attachments": "Images and files",
|
||||
"ui.promptInput.context": "Context",
|
||||
@@ -140,6 +141,9 @@ const source = {
|
||||
"ui.promptInput.chooseVariant": "Choose model variant",
|
||||
"ui.promptInput.send": "Send",
|
||||
"ui.promptInput.stop": "Stop",
|
||||
"ui.promptInput.steer": "Steer",
|
||||
"ui.promptInput.queue": "Queue",
|
||||
"ui.promptInput.steerHint": "Send without interrupting",
|
||||
|
||||
"ui.tabs.close": "Close tab",
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
:root {
|
||||
--font-family-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--font-family-sans: "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--font-family-sans--font-feature-settings: normal;
|
||||
--font-family-mono:
|
||||
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
--font-family-mono--font-feature-settings: normal;
|
||||
|
||||
--font-size-small: 13px;
|
||||
|
||||
@@ -129,9 +129,9 @@
|
||||
--v2-illustration-illustration-layer-02: var(--v2-grey-400);
|
||||
--v2-illustration-illustration-layer-03: var(--v2-grey-500);
|
||||
|
||||
--font-family-text: "Inter", sans-serif;
|
||||
--v2-font-family-sans: "Inter", sans-serif;
|
||||
--v2-font-family-code: "IBM Plex Mono", var(--font-family-mono);
|
||||
--font-family-text: var(--font-family-sans);
|
||||
--v2-font-family-sans: var(--font-family-sans);
|
||||
--v2-font-family-code: var(--font-family-mono);
|
||||
--line-height-tight: 12px;
|
||||
--line-height-compact: 16px;
|
||||
--line-height-base: 20px;
|
||||
|
||||
@@ -57,20 +57,19 @@ Or you can set it up manually.
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run OpenCode
|
||||
- name: Run OpenCode
|
||||
uses: anomalyco/opencode/github@latest
|
||||
env:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
with:
|
||||
model: anthropic/claude-sonnet-4-20250514
|
||||
# share: true
|
||||
# github_token: xxxx
|
||||
```
|
||||
|
||||
3. **Store the API keys in secrets**
|
||||
@@ -85,19 +84,30 @@ Or you can set it up manually.
|
||||
- `agent`: The agent to use. Must be a primary agent. Falls back to `default_agent` from config or `"build"` if not found.
|
||||
- `share`: Whether to share the OpenCode session. Defaults to **true** for public repositories.
|
||||
- `prompt`: Optional custom prompt to override the default behavior. Use this to customize how OpenCode processes requests.
|
||||
- `token`: Optional GitHub access token for performing operations such as creating comments, committing changes, and opening pull requests. By default, OpenCode uses the installation access token from the OpenCode GitHub App, so commits, comments, and pull requests appear as coming from the app.
|
||||
- `mentions`: Comma-separated list of trigger phrases, case-insensitive. Defaults to `/opencode,/oc`.
|
||||
- `variant`: Model variant for provider-specific reasoning effort, for example `high`, `max`, or `minimal`.
|
||||
- `oidc_base_url`: Base URL for the OIDC token exchange API. Only needed when running a custom GitHub App install. Defaults to `https://api.opencode.ai`.
|
||||
- `use_github_token`: Set to `true` to use a caller-provided `GITHUB_TOKEN` instead of exchanging an OIDC token for an OpenCode App installation token. Defaults to `false`.
|
||||
|
||||
Alternatively, you can use the GitHub Action runner's [built-in `GITHUB_TOKEN`](https://docs.github.com/en/actions/tutorials/authenticate-with-github_token) without installing the OpenCode GitHub App. Just make sure to grant the required permissions in your workflow:
|
||||
Use this mode to run without installing the OpenCode GitHub App. Pass the token through `env` and grant the permissions required by your workflow:
|
||||
|
||||
```yaml
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
steps:
|
||||
- uses: anomalyco/opencode/github@latest
|
||||
env:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
model: anthropic/claude-sonnet-4-20250514
|
||||
use_github_token: true
|
||||
```
|
||||
|
||||
You can also use a [personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)(PAT) if preferred.
|
||||
`id-token: write` is not required in this mode because OIDC exchange is skipped. To use a [personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) or another GitHub App token, store it as a secret and pass that secret as `GITHUB_TOKEN` instead.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10614,6 +10614,104 @@
|
||||
"summary": "Refresh worktrees"
|
||||
}
|
||||
},
|
||||
"/api/workspace": {
|
||||
"post": {
|
||||
"tags": ["workspace"],
|
||||
"operationId": "v2.workspace.create",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"pattern": "^wrk"
|
||||
}
|
||||
},
|
||||
"required": ["data"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "ProviderNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProviderNotFoundErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "ConflictError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ConflictErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Create a logical workspace. A caller-supplied ID is idempotent when retried with the same provider; reusing it with another provider returns a conflict.",
|
||||
"summary": "Create workspace",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^wrk"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"provider": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["provider"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/workspace/{workspaceID}": {
|
||||
"delete": {
|
||||
"tags": ["workspace"],
|
||||
|
||||
@@ -10614,6 +10614,104 @@
|
||||
"summary": "Refresh worktrees"
|
||||
}
|
||||
},
|
||||
"/api/workspace": {
|
||||
"post": {
|
||||
"tags": ["workspace"],
|
||||
"operationId": "v2.workspace.create",
|
||||
"parameters": [],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "string",
|
||||
"pattern": "^wrk"
|
||||
}
|
||||
},
|
||||
"required": ["data"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "ProviderNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProviderNotFoundErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "ConflictError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ConflictErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Create a logical workspace. A caller-supplied ID is idempotent when retried with the same provider; reusing it with another provider returns a conflict.",
|
||||
"summary": "Create workspace",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^wrk"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"provider": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["provider"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/workspace/{workspaceID}": {
|
||||
"delete": {
|
||||
"tags": ["workspace"],
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: "Effect"
|
||||
---
|
||||
|
||||
`@opencode-ai/client/effect` is the Effect-native client for the OpenCode HTTP API. It returns typed Effects and Streams
|
||||
and decodes responses into OpenCode schema values.
|
||||
|
||||
```sh
|
||||
bun add @opencode-ai/client@beta effect
|
||||
```
|
||||
|
||||
## Create a client
|
||||
|
||||
Create a client with the server URL, then call methods grouped by API resource.
|
||||
|
||||
```ts
|
||||
import { AbsolutePath, Location, OpenCode } from "@opencode-ai/client/effect"
|
||||
import { Effect } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const client = yield* OpenCode.make({ baseUrl: "http://localhost:4096" })
|
||||
const session = yield* client.session.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make("/workspace") }),
|
||||
})
|
||||
yield* client.session.prompt({
|
||||
sessionID: session.id,
|
||||
text: "Review the current changes",
|
||||
})
|
||||
return session
|
||||
})
|
||||
|
||||
const session = await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer)))
|
||||
```
|
||||
|
||||
## Headers and requests
|
||||
|
||||
Pass default headers to `OpenCode.make`. Each operation also accepts request options for cancellation or per-request
|
||||
headers.
|
||||
|
||||
```ts
|
||||
const client = yield* OpenCode.make({
|
||||
baseUrl: "https://opencode.example.com",
|
||||
headers: { authorization: `Bearer ${process.env.OPENCODE_TOKEN}` },
|
||||
})
|
||||
|
||||
const sessions = yield* client.session.list(undefined, {
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
})
|
||||
```
|
||||
|
||||
## Stream events
|
||||
|
||||
Streaming operations such as `event.subscribe()` and `session.log()` return Effect Streams.
|
||||
|
||||
```ts
|
||||
import { Effect, Stream } from "effect"
|
||||
|
||||
yield* client.event.subscribe().pipe(
|
||||
Stream.runForEach((event) => Effect.logInfo("OpenCode event", { type: event.type })),
|
||||
)
|
||||
```
|
||||
|
||||
## Local background service
|
||||
|
||||
The Node-only `@opencode-ai/client/effect/service` entrypoint discovers, starts, authenticates, and stops the local
|
||||
background service as Effects.
|
||||
|
||||
```sh
|
||||
bun add @effect/platform-node
|
||||
```
|
||||
|
||||
Create an authenticated client for the ensured service.
|
||||
|
||||
```ts
|
||||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { OpenCode } from "@opencode-ai/client/effect"
|
||||
import { Service } from "@opencode-ai/client/effect/service"
|
||||
import { Effect } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const endpoint = yield* Service.ensure()
|
||||
const client = yield* OpenCode.make({
|
||||
baseUrl: endpoint.url,
|
||||
headers: Service.headers(endpoint),
|
||||
})
|
||||
return yield* client.health.get()
|
||||
})
|
||||
|
||||
const health = await Effect.runPromise(
|
||||
program.pipe(Effect.provide(FetchHttpClient.layer), Effect.provide(NodeFileSystem.layer)),
|
||||
)
|
||||
```
|
||||
|
||||
Discover without starting, or stop the exact registered service.
|
||||
|
||||
```ts
|
||||
const endpoint = yield* Service.discover()
|
||||
yield* Service.stop()
|
||||
```
|
||||
+1
-66
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: "Client"
|
||||
title: "JavaScript"
|
||||
---
|
||||
|
||||
`@opencode-ai/client` is the generated TypeScript client for the OpenCode HTTP
|
||||
@@ -110,68 +110,3 @@ const endpoint = await Service.ensure({
|
||||
|
||||
Omit these options to use the standard registration path and
|
||||
`opencode serve --service` command.
|
||||
|
||||
## Effect
|
||||
|
||||
OpenCode provides a first-class Effect client through the
|
||||
`@opencode-ai/client/effect` entrypoint. It returns typed Effects and Streams
|
||||
and decodes responses into OpenCode schema values.
|
||||
|
||||
```sh
|
||||
bun add @opencode-ai/client@beta effect
|
||||
```
|
||||
|
||||
### Create a client
|
||||
|
||||
```ts
|
||||
import { AbsolutePath, Location, OpenCode } from "@opencode-ai/client/effect"
|
||||
import { Effect } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const client = yield* OpenCode.make({ baseUrl: "http://localhost:4096" })
|
||||
const session = yield* client.session.create({
|
||||
location: Location.Ref.make({
|
||||
directory: AbsolutePath.make("/workspace"),
|
||||
}),
|
||||
})
|
||||
|
||||
return yield* client.session.get({ sessionID: session.id })
|
||||
})
|
||||
|
||||
const session = await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer)))
|
||||
```
|
||||
|
||||
Streaming operations, including `client.event.subscribe()` and
|
||||
`client.session.log(...)`, return Effect `Stream` values.
|
||||
|
||||
### Local background service
|
||||
|
||||
The Node-only `@opencode-ai/client/effect/service` entrypoint exposes the same
|
||||
operations as Effect values. Add `@effect/platform-node` and provide its
|
||||
filesystem layer when running them.
|
||||
|
||||
```sh
|
||||
bun add @effect/platform-node
|
||||
```
|
||||
|
||||
```ts
|
||||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { OpenCode } from "@opencode-ai/client/effect"
|
||||
import { Service } from "@opencode-ai/client/effect/service"
|
||||
import { Effect } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const endpoint = yield* Service.ensure()
|
||||
const client = yield* OpenCode.make({
|
||||
baseUrl: endpoint.url,
|
||||
headers: Service.headers(endpoint),
|
||||
})
|
||||
return yield* client.health.get()
|
||||
})
|
||||
|
||||
const health = await Effect.runPromise(
|
||||
program.pipe(Effect.provide(FetchHttpClient.layer), Effect.provide(NodeFileSystem.layer)),
|
||||
)
|
||||
```
|
||||
@@ -2,6 +2,10 @@
|
||||
title: "Intro"
|
||||
---
|
||||
|
||||
OpenCode is used by millions every day. Build on top of it to create your own
|
||||
applications, integrations, and agent experiences without starting from
|
||||
scratch.
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Extend OpenCode" href="/build/plugins">
|
||||
Build plugins that add tools, integrations, commands, agents, and custom behavior while keeping the rest of OpenCode
|
||||
|
||||
@@ -15,6 +15,9 @@ export default Plugin.define({
|
||||
})
|
||||
```
|
||||
|
||||
Import `@opencode-ai/plugin/tui` directly. OpenCode resolves this import at runtime, so local CLI plugins do not need an
|
||||
absolute path to an OpenCode checkout.
|
||||
|
||||
## Context
|
||||
|
||||
`setup` receives configuration, app metadata, the current location, the OpenCode client, cached data, theme tokens, the
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
---
|
||||
title: "SDK"
|
||||
---
|
||||
|
||||
`@opencode-ai/sdk` hosts OpenCode directly inside your application. Unlike the
|
||||
[network client](/build/client), it assembles the OpenCode server and routes API
|
||||
calls through its HTTP router in memory. It opens no HTTP listener and adds no
|
||||
network hop between the client and server.
|
||||
|
||||
<Callout type="warning">
|
||||
The V2 SDK is beta. Install the current preview with `bun add @opencode-ai/sdk@dev`; its API may change before a
|
||||
stable release.
|
||||
</Callout>
|
||||
|
||||
## Create a host
|
||||
|
||||
`OpenCode.create()` returns an explicitly owned host. Use `await using` to
|
||||
release its router, Location services, fibers, and scoped plugin registrations:
|
||||
|
||||
```ts
|
||||
import { OpenCode } from "@opencode-ai/sdk"
|
||||
|
||||
await using opencode = await OpenCode.create()
|
||||
const session = await opencode.sessions.create({
|
||||
location: { directory: "/workspace" },
|
||||
})
|
||||
|
||||
await opencode.sessions.prompt({
|
||||
sessionID: session.id,
|
||||
text: "Review the current changes",
|
||||
})
|
||||
```
|
||||
|
||||
Call `await opencode.close()` explicitly when explicit resource management is
|
||||
not available.
|
||||
|
||||
The embedded host uses the same Promise values, declared errors, request
|
||||
options, and `AsyncIterable` streams as `@opencode-ai/client`. It exposes the
|
||||
full generated client and adds the convenience aliases `sessions` and `events`
|
||||
for the session and event groups.
|
||||
|
||||
## Stream events
|
||||
|
||||
```ts
|
||||
for await (const event of opencode.events.subscribe()) {
|
||||
console.log(event.type)
|
||||
}
|
||||
```
|
||||
|
||||
Pass an `AbortSignal` through the generated request options, or leave an
|
||||
iteration to cancel its response body.
|
||||
|
||||
## Register plugins
|
||||
|
||||
Pass initial Promise plugins to `OpenCode.create()`. Embedded plugins use the
|
||||
same discovery and Location-scoped activation path as configured plugins.
|
||||
|
||||
```ts
|
||||
const plugin = {
|
||||
id: "example",
|
||||
async setup(ctx) {
|
||||
await ctx.agent.transform((agents) => {
|
||||
// Modify the Location's agent catalog.
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
await using opencode = await OpenCode.create({ plugins: [plugin] })
|
||||
```
|
||||
|
||||
Call `await opencode.plugin(plugin)` to register another plugin after startup.
|
||||
|
||||
See the [Plugins guide](/build/plugins) for the plugin context and available
|
||||
hooks.
|
||||
|
||||
## Workerd
|
||||
|
||||
Use `@opencode-ai/sdk/workerd` inside a Cloudflare Durable Object. This profile
|
||||
uses the object's SQLite storage, persists durable events for eviction recovery,
|
||||
and replaces unavailable local filesystem and process services.
|
||||
|
||||
Hold one host for the lifetime of the Durable Object instance instead of
|
||||
creating one for every request:
|
||||
|
||||
```ts
|
||||
import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
|
||||
import myPlugin from "./my-plugin"
|
||||
|
||||
export class OpenCodeDO {
|
||||
private readonly opencode: Promise<OpenCodeWorkerd.Interface>
|
||||
|
||||
constructor(state: DurableObjectState) {
|
||||
this.opencode = state.blockConcurrencyWhile(() =>
|
||||
OpenCodeWorkerd.create({
|
||||
storage: state.storage,
|
||||
config: { default_agent: "build" },
|
||||
plugins: [myPlugin],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async fetch() {
|
||||
const opencode = await this.opencode
|
||||
return Response.json(await opencode.health.get())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`blockConcurrencyWhile` keeps every Durable Object event out until the host is
|
||||
ready and resets the object if initialization fails. The retained Promise gives
|
||||
request handlers direct access to the same host after startup. Configuration is
|
||||
a typed JavaScript object, and plugins are imported values bundled with the
|
||||
Worker.
|
||||
|
||||
Wrangler selects OpenCode's Workerd-safe low-level implementations through the
|
||||
`workerd` package condition. Cloudflare may evict a Durable Object without
|
||||
running cleanup, so correctness does not depend on `close()` being called.
|
||||
|
||||
## Effect
|
||||
|
||||
Import the Effect-native API from `@opencode-ai/sdk/effect`. Closing its Effect
|
||||
Scope releases the embedded host:
|
||||
|
||||
```ts
|
||||
import { AbsolutePath, Location, OpenCode } from "@opencode-ai/sdk/effect"
|
||||
import { Effect } from "effect"
|
||||
|
||||
const program = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const opencode = yield* OpenCode.create()
|
||||
return yield* opencode.sessions.create({
|
||||
location: Location.Ref.make({
|
||||
directory: AbsolutePath.make("/workspace"),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
const session = await Effect.runPromise(program)
|
||||
```
|
||||
|
||||
Effect applications can contribute plugins from ordinary registration layers.
|
||||
The registration layer may depend on `OpenCode.Service` and any other services
|
||||
needed to construct the plugin; `OpenCode.layer()` remains unaware of those
|
||||
features.
|
||||
|
||||
Use `OpenCode.layer()` for dependency injection. The Effect-native Workerd
|
||||
entrypoint is `@opencode-ai/sdk/workerd/effect`.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: "Cloudflare"
|
||||
---
|
||||
|
||||
Use `@opencode-ai/sdk/workerd` inside a Cloudflare Durable Object. This profile uses the object's SQLite storage,
|
||||
persists durable events for eviction recovery, and replaces unavailable local filesystem and process services.
|
||||
|
||||
```sh
|
||||
bun add @opencode-ai/sdk@dev
|
||||
```
|
||||
|
||||
Hold one host for the lifetime of the Durable Object instance instead of creating one for every request.
|
||||
|
||||
```ts
|
||||
import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
|
||||
import myPlugin from "./my-plugin"
|
||||
|
||||
export class OpenCodeDO {
|
||||
private readonly opencode: Promise<OpenCodeWorkerd.Interface>
|
||||
|
||||
constructor(state: DurableObjectState) {
|
||||
this.opencode = state.blockConcurrencyWhile(() =>
|
||||
OpenCodeWorkerd.create({
|
||||
storage: state.storage,
|
||||
config: { default_agent: "build" },
|
||||
plugins: [myPlugin],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async fetch() {
|
||||
const opencode = await this.opencode
|
||||
return Response.json(await opencode.health.get())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`blockConcurrencyWhile` keeps every Durable Object event out until the host is ready and resets the object if
|
||||
initialization fails. The retained Promise gives request handlers direct access to the same host after startup.
|
||||
|
||||
```ts
|
||||
constructor(state: DurableObjectState) {
|
||||
this.opencode = state.blockConcurrencyWhile(() =>
|
||||
OpenCodeWorkerd.create({ storage: state.storage }),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Wrangler selects OpenCode's Workerd-safe implementations through the `workerd` package condition. Cloudflare may evict
|
||||
a Durable Object without running cleanup, so correctness does not depend on `close()` being called.
|
||||
|
||||
```jsonc title="wrangler.jsonc"
|
||||
{
|
||||
"compatibility_flags": ["nodejs_compat"]
|
||||
}
|
||||
```
|
||||
|
||||
## Customize
|
||||
|
||||
Customize your OpenCode instance by registering plugins bundled with your
|
||||
Worker. Pass plugins to `OpenCodeWorkerd.create()` to customize agents, models,
|
||||
tools, and other behavior:
|
||||
|
||||
```ts
|
||||
import { Plugin } from "@opencode-ai/plugin"
|
||||
import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
|
||||
|
||||
const plugin = Plugin.define({
|
||||
id: "customize-agent",
|
||||
async setup(ctx) {
|
||||
await ctx.agent.transform((agents) => {
|
||||
agents.update("build", (agent) => {
|
||||
agent.description = "Builds features and fixes bugs for our team"
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
await OpenCodeWorkerd.create({
|
||||
storage: state.storage,
|
||||
config: { default_agent: "build" },
|
||||
plugins: [plugin],
|
||||
})
|
||||
```
|
||||
|
||||
See the [full plugins documentation](/build/plugins) for plugin hooks,
|
||||
transforms, tools, and the complete plugin context.
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: "Effect"
|
||||
---
|
||||
|
||||
`@opencode-ai/sdk/effect` is the Effect-native embedded SDK. Operations return typed Effects and Streams, and closing
|
||||
the owning Scope releases the router, Location services, fibers, and plugin registrations.
|
||||
|
||||
```sh
|
||||
bun add @opencode-ai/sdk@dev effect
|
||||
```
|
||||
|
||||
## Create a host
|
||||
|
||||
Create the host inside `Effect.scoped`, then use its generated API groups or the `sessions` alias.
|
||||
|
||||
```ts
|
||||
import { AbsolutePath, Location, OpenCode } from "@opencode-ai/sdk/effect"
|
||||
import { Effect } from "effect"
|
||||
|
||||
const program = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const opencode = yield* OpenCode.create()
|
||||
const session = yield* opencode.sessions.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make("/workspace") }),
|
||||
})
|
||||
yield* opencode.sessions.prompt({
|
||||
sessionID: session.id,
|
||||
text: "Review the current changes",
|
||||
})
|
||||
return session
|
||||
}),
|
||||
)
|
||||
|
||||
const session = await Effect.runPromise(program)
|
||||
```
|
||||
|
||||
The embedded host uses the same schema values, declared errors, request options, and Streams as
|
||||
`@opencode-ai/client/effect`.
|
||||
|
||||
```ts
|
||||
const health = yield* opencode.health.get()
|
||||
const sessions = yield* opencode.sessions.list()
|
||||
```
|
||||
|
||||
## Stream events
|
||||
|
||||
Streaming endpoints return Effect `Stream` values. Fork consumers in the host Scope when they should run in the
|
||||
background.
|
||||
|
||||
```ts
|
||||
import { Effect, Stream } from "effect"
|
||||
|
||||
yield* opencode.events.subscribe().pipe(
|
||||
Stream.runForEach((event) => Effect.logInfo("OpenCode event", { type: event.type })),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
```
|
||||
|
||||
## Customize
|
||||
|
||||
Customize your OpenCode instance by registering Effect plugins. Use the embedded
|
||||
host to customize agents, models, tools, and other behavior:
|
||||
|
||||
```ts
|
||||
import { Plugin } from "@opencode-ai/plugin/effect"
|
||||
import { Effect } from "effect"
|
||||
|
||||
const plugin = Plugin.define({
|
||||
id: "customize-agent",
|
||||
effect: (ctx) =>
|
||||
Effect.gen(function* () {
|
||||
const agent = ctx.agent
|
||||
yield* agent.transform((agents) => {
|
||||
agents.update("build", (agent) => {
|
||||
agent.description = "Builds features and fixes bugs for our team"
|
||||
})
|
||||
})
|
||||
}),
|
||||
})
|
||||
|
||||
yield* opencode.plugin(plugin)
|
||||
```
|
||||
|
||||
See the [full Effect plugins documentation](/build/plugins/effect) for plugin
|
||||
hooks, transforms, tools, and the complete plugin context.
|
||||
|
||||
## Layer
|
||||
|
||||
Use `OpenCode.layer()` when the embedded host should be an application service.
|
||||
|
||||
```ts
|
||||
import { OpenCode } from "@opencode-ai/sdk/effect"
|
||||
import { Effect } from "effect"
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const opencode = yield* OpenCode.Service
|
||||
return yield* opencode.health.get()
|
||||
})
|
||||
|
||||
const health = await Effect.runPromise(program.pipe(Effect.provide(OpenCode.layer())))
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: "Overview"
|
||||
---
|
||||
|
||||
`@opencode-ai/sdk` hosts OpenCode directly inside your application. Unlike the
|
||||
[network client](/build/client), it assembles the OpenCode server and routes API
|
||||
calls through its HTTP router in memory. It opens no HTTP listener and adds no
|
||||
network hop between the client and server.
|
||||
|
||||
<Callout type="warning">
|
||||
The V2 SDK is beta. Install the current preview with `bun add @opencode-ai/sdk@dev`; its API may change before a
|
||||
stable release.
|
||||
</Callout>
|
||||
|
||||
## Create a host
|
||||
|
||||
`OpenCode.create()` returns an explicitly owned host. Use `await using` to
|
||||
release its router, Location services, fibers, and scoped plugin registrations:
|
||||
|
||||
```ts
|
||||
import { OpenCode } from "@opencode-ai/sdk"
|
||||
|
||||
await using opencode = await OpenCode.create()
|
||||
const session = await opencode.sessions.create({
|
||||
location: { directory: "/workspace" },
|
||||
})
|
||||
|
||||
await opencode.sessions.prompt({
|
||||
sessionID: session.id,
|
||||
text: "Review the current changes",
|
||||
})
|
||||
```
|
||||
|
||||
Call `await opencode.close()` explicitly when explicit resource management is
|
||||
not available.
|
||||
|
||||
The embedded host uses the same Promise values, declared errors, request
|
||||
options, and `AsyncIterable` streams as `@opencode-ai/client`. It exposes the
|
||||
full generated client and adds the convenience aliases `sessions` and `events`
|
||||
for the session and event groups.
|
||||
|
||||
## Stream events
|
||||
|
||||
```ts
|
||||
for await (const event of opencode.events.subscribe()) {
|
||||
console.log(event.type)
|
||||
}
|
||||
```
|
||||
|
||||
Pass an `AbortSignal` through the generated request options, or leave an
|
||||
iteration to cancel its response body.
|
||||
|
||||
## Customize
|
||||
|
||||
Customize your OpenCode instance by registering plugins. Pass plugins to
|
||||
`OpenCode.create()` to customize agents, models, tools, and other behavior when
|
||||
the embedded host starts:
|
||||
|
||||
```ts
|
||||
import { Plugin } from "@opencode-ai/plugin"
|
||||
import { OpenCode } from "@opencode-ai/sdk"
|
||||
|
||||
const plugin = Plugin.define({
|
||||
id: "customize-agent",
|
||||
async setup(ctx) {
|
||||
await ctx.agent.transform((agents) => {
|
||||
agents.update("build", (agent) => {
|
||||
agent.description = "Builds features and fixes bugs for our team"
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
await using opencode = await OpenCode.create({ plugins: [plugin] })
|
||||
```
|
||||
|
||||
Call `await opencode.plugin(plugin)` to register another plugin after startup.
|
||||
|
||||
See the [full plugins documentation](/build/plugins) for plugin hooks,
|
||||
transforms, tools, and the complete plugin context.
|
||||
@@ -54,3 +54,6 @@ OpenCode also discovers JavaScript and TypeScript plugins from `plugins/tui` und
|
||||
<global-config>/plugins/tui/status.ts
|
||||
<project>/.opencode/plugins/tui/status.ts
|
||||
```
|
||||
|
||||
Discovered plugins can import `@opencode-ai/plugin/tui` directly; OpenCode resolves the package at runtime. See
|
||||
[Building CLI plugins](/build/plugins/cli) for examples.
|
||||
|
||||
@@ -128,9 +128,9 @@ agents.
|
||||
### Autoupdate
|
||||
|
||||
Control automatic updates from the global config. Set this to `false` to
|
||||
disable updates. The current beta treats `true` and `"notify"` identically and
|
||||
automatically installs compatible non-major updates; project-level values are
|
||||
ignored.
|
||||
disable updates, or `"notify"` to report available updates without installing
|
||||
them. Set this to `true` to automatically install compatible non-major updates.
|
||||
Project-level values are ignored.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
|
||||
@@ -88,7 +88,7 @@ export const docsSections: DocsSection[] = [
|
||||
landingSlug: "build",
|
||||
groups: [
|
||||
{
|
||||
items: [{ title: "Build", slug: "build" }],
|
||||
items: [{ title: "Intro", slug: "build" }],
|
||||
},
|
||||
{
|
||||
title: "Plugins",
|
||||
@@ -99,9 +99,18 @@ export const docsSections: DocsSection[] = [
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Client",
|
||||
items: [
|
||||
{ title: "Client", slug: "build/client" },
|
||||
{ title: "SDK", slug: "build/sdk" },
|
||||
{ title: "JavaScript", slug: "build/client" },
|
||||
{ title: "Effect", slug: "build/client/effect" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "SDK",
|
||||
items: [
|
||||
{ title: "Overview", slug: "build/sdk" },
|
||||
{ title: "Effect", slug: "build/sdk/effect" },
|
||||
{ title: "Cloudflare", slug: "build/sdk/cloudflare" },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user