mirror of
https://github.com/anomalyco/opencode.git
synced 2026-09-04 16:06:23 +00:00
Compare commits
20
Commits
sidebar-status
...
beta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b09a74591c | ||
|
|
e8481973ce | ||
|
|
211cd73f1a | ||
|
|
2375e81bd6 | ||
|
|
8352addf6c | ||
|
|
32f89748af | ||
|
|
89478b36f1 | ||
|
|
46458f0753 | ||
|
|
c907d2ba27 | ||
|
|
ffac1c5b11 | ||
|
|
c5dca2df37 | ||
|
|
8889447f5a | ||
|
|
a1cb005799 | ||
|
|
19833ad1fd | ||
|
|
cb852434b1 | ||
|
|
b3733e9517 | ||
|
|
331f4ecd2f | ||
|
|
ecaa914b79 | ||
|
|
4f8dea674a | ||
|
|
4bf5269c4c |
@@ -11,7 +11,7 @@
|
||||
// Manual `cache: CacheHint` placements on individual parts are preserved and
|
||||
// count against the four-breakpoint budget; auto only fills remaining slots.
|
||||
import { CacheHint, type CachePolicy, type CachePolicyObject } from "./schema/options.js"
|
||||
import { LLMRequest, Message, ToolDefinition, type ContentPart } from "./schema/messages.js"
|
||||
import { LLMRequest, Message, ToolDefinition, type ContentPart, type ToolEntry } from "./schema/messages.js"
|
||||
|
||||
const AUTO: CachePolicyObject = {
|
||||
tools: true,
|
||||
@@ -50,18 +50,24 @@ interface Budget {
|
||||
remaining: number
|
||||
}
|
||||
|
||||
const markLastTool = (
|
||||
tools: ReadonlyArray<ToolDefinition>,
|
||||
hint: CacheHint,
|
||||
budget: Budget,
|
||||
): ReadonlyArray<ToolDefinition> => {
|
||||
if (tools.length === 0) return tools
|
||||
const last = tools.length - 1
|
||||
if (tools[last]!.cache || budget.remaining === 0) return tools
|
||||
const markLastTool = (tools: ReadonlyArray<ToolEntry>, hint: CacheHint, budget: Budget): ReadonlyArray<ToolEntry> => {
|
||||
const target = tools.at(-1)
|
||||
if (target === undefined) return tools
|
||||
if (target.type === "namespace") {
|
||||
const nested = markLastTool(target.tools, hint, budget)
|
||||
return nested === target.tools ? tools : [...tools.slice(0, -1), { ...target, tools: nested }]
|
||||
}
|
||||
if (target.cache || budget.remaining === 0) return tools
|
||||
budget.remaining -= 1
|
||||
return tools.map((tool, i) => (i === last ? new ToolDefinition({ ...tool, cache: hint }) : tool))
|
||||
return [...tools.slice(0, -1), new ToolDefinition({ ...target, cache: hint })]
|
||||
}
|
||||
|
||||
const countToolHints = (tools: ReadonlyArray<ToolEntry>): number =>
|
||||
tools.reduce(
|
||||
(count, tool) => count + (tool.type === "tool" ? (tool.cache === undefined ? 0 : 1) : countToolHints(tool.tools)),
|
||||
0,
|
||||
)
|
||||
|
||||
const markSystemBoundaries = (system: LLMRequest["system"], hint: CacheHint, budget: Budget): LLMRequest["system"] => {
|
||||
if (system.length === 0) return system
|
||||
let changed = false
|
||||
@@ -122,7 +128,7 @@ const markMessages = (
|
||||
}
|
||||
|
||||
const countHints = (request: LLMRequest) =>
|
||||
request.tools.reduce((count, tool) => count + (tool.cache === undefined ? 0 : 1), 0) +
|
||||
countToolHints(request.tools) +
|
||||
request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) +
|
||||
request.messages.reduce(
|
||||
(count, message) =>
|
||||
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
LanguageModel,
|
||||
SystemPart,
|
||||
ToolChoice,
|
||||
ToolDefinition,
|
||||
ToolEntry,
|
||||
type ContentPart,
|
||||
type LanguageModelProviderOptions,
|
||||
type ToolEntryInput,
|
||||
} from "./schema/index.js"
|
||||
import { make as makeTool, toDefinitions, type ToolSchema } from "./tool.js"
|
||||
|
||||
@@ -27,7 +28,7 @@ export type RequestInput<SelectedLanguageModel extends LanguageModel = LanguageM
|
||||
readonly system?: string | SystemPart | ReadonlyArray<SystemPart>
|
||||
readonly prompt?: string | ContentPart | ReadonlyArray<ContentPart>
|
||||
readonly messages?: ReadonlyArray<Message | Message.Input>
|
||||
readonly tools?: ReadonlyArray<ToolDefinition.Input>
|
||||
readonly tools?: ReadonlyArray<ToolEntryInput>
|
||||
readonly toolChoice?: ToolChoice.Input
|
||||
readonly generation?: GenerationOptions.Input
|
||||
readonly providerOptions?: NoInfer<LanguageModelProviderOptions<SelectedLanguageModel>>
|
||||
@@ -56,7 +57,7 @@ export const request = <const SelectedLanguageModel extends LanguageModel>(
|
||||
...rest,
|
||||
system: SystemPart.content(requestSystem),
|
||||
messages: [...(messages?.map(Message.make) ?? []), ...(prompt === undefined ? [] : [Message.user(prompt)])],
|
||||
tools: tools?.map(ToolDefinition.make) ?? [],
|
||||
tools: tools?.map(ToolEntry.make) ?? [],
|
||||
toolChoice: requestToolChoice ? ToolChoice.make(requestToolChoice) : undefined,
|
||||
generation: requestGeneration === undefined ? undefined : GenerationOptions.make(requestGeneration),
|
||||
providerOptions: requestProviderOptions,
|
||||
|
||||
@@ -1067,10 +1067,11 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
|
||||
// messages. Tools live highest in the cache hierarchy, so when callers
|
||||
// over-mark we keep their tool hints and shed the message-tail ones first.
|
||||
const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
const tools =
|
||||
request.tools.length === 0
|
||||
flattened.tools.length === 0
|
||||
? undefined
|
||||
: request.tools.map((tool) =>
|
||||
: flattened.tools.map((tool) =>
|
||||
lowerTool(
|
||||
breakpoints,
|
||||
tool,
|
||||
@@ -1088,7 +1089,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
|
||||
text: part.text,
|
||||
cache_control: cacheControl(breakpoints, part.cache),
|
||||
}))
|
||||
const messages = yield* lowerMessages(request, breakpoints)
|
||||
const messages = yield* lowerMessages(flattened.request, breakpoints)
|
||||
if (breakpoints.dropped > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`Anthropic Messages: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${ANTHROPIC_BREAKPOINT_CAP} per request.`,
|
||||
|
||||
@@ -427,21 +427,22 @@ const lowerSystem = (
|
||||
|
||||
const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: LLMRequest) {
|
||||
const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
const generation = request.generation
|
||||
// Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in
|
||||
// tools → system → messages order to favour the highest-impact prefixes.
|
||||
const breakpoints = BedrockCache.breakpoints()
|
||||
const toolConfig = (() => {
|
||||
if (request.tools.length === 0) return undefined
|
||||
if (flattened.tools.length === 0) return undefined
|
||||
return {
|
||||
tools: lowerTools(request.model.compatibility?.toolSchema, breakpoints, request.tools),
|
||||
tools: lowerTools(request.model.compatibility?.toolSchema, breakpoints, flattened.tools),
|
||||
// Converse has no native "none". Keep definitions stable for prompt
|
||||
// caching and omit only the unsupported choice.
|
||||
toolChoice,
|
||||
}
|
||||
})()
|
||||
const system = lowerSystem(breakpoints, request.system)
|
||||
const messages = yield* lowerMessages(request, breakpoints)
|
||||
const messages = yield* lowerMessages(flattened.request, breakpoints)
|
||||
if (breakpoints.dropped > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`Bedrock Converse: dropped ${breakpoints.dropped} cache breakpoint(s); the API allows at most ${BedrockCache.BEDROCK_BREAKPOINT_CAP} per request.`,
|
||||
@@ -508,7 +509,6 @@ const mapUsage = (usage: BedrockUsageSchema | undefined, providerMetadataKey: st
|
||||
interface ParserState {
|
||||
readonly providerMetadataKey: string
|
||||
readonly tools: ToolStream.State<number>
|
||||
readonly finishedTools: ReadonlySet<number>
|
||||
// Bedrock splits the finish into `messageStop` (carries `stopReason`) and
|
||||
// `metadata` (carries usage). Hold both in state so `onHalt` can emit exactly
|
||||
// one finish after both chunks have had a chance to arrive.
|
||||
@@ -620,16 +620,14 @@ const step = (state: ParserState, event: BedrockEvent) =>
|
||||
}
|
||||
|
||||
if (event.contentBlockDelta?.delta?.toolUse) {
|
||||
const index = event.contentBlockDelta.contentBlockIndex
|
||||
if (state.finishedTools.has(index)) return [state, []] as const
|
||||
const result = ToolStream.appendExisting(
|
||||
ADAPTER,
|
||||
// A delta for a block that is not open, whether it already stopped or never
|
||||
// started, has nothing to attach to and is dropped.
|
||||
const result = ToolStream.append(
|
||||
state.tools,
|
||||
index,
|
||||
event.contentBlockDelta.contentBlockIndex,
|
||||
event.contentBlockDelta.delta.toolUse.input,
|
||||
"Bedrock Converse tool delta is missing its tool call",
|
||||
)
|
||||
if (ToolStream.isError(result)) return yield* result
|
||||
if (!result) return [state, []] as const
|
||||
const events: LLMEvent[] = []
|
||||
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
||||
events.push(...result.events)
|
||||
@@ -668,7 +666,6 @@ const step = (state: ParserState, event: BedrockEvent) =>
|
||||
state.hasToolCalls,
|
||||
lifecycle,
|
||||
tools: result.tools,
|
||||
finishedTools: resultEvents.length > 0 ? new Set([...state.finishedTools, index]) : state.finishedTools,
|
||||
reasoningSignatures: Object.fromEntries(
|
||||
Object.entries(state.reasoningSignatures).filter(([key]) => key !== String(index)),
|
||||
),
|
||||
@@ -765,7 +762,6 @@ export const protocol = Protocol.make({
|
||||
initial: (request) => ({
|
||||
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
|
||||
tools: ToolStream.empty<number>(),
|
||||
finishedTools: new Set<number>(),
|
||||
finishReason: undefined,
|
||||
usage: undefined,
|
||||
hasToolCalls: false,
|
||||
|
||||
@@ -465,7 +465,8 @@ function mapSafetySettings(value: unknown) {
|
||||
}
|
||||
|
||||
const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) {
|
||||
const hasTools = request.tools.length > 0
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
const hasTools = flattened.tools.length > 0
|
||||
const generation = request.generation
|
||||
const options = resolveOptions(request)
|
||||
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
|
||||
@@ -483,7 +484,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
|
||||
|
||||
return {
|
||||
cachedContent: options.cachedContent,
|
||||
contents: yield* lowerMessages(request),
|
||||
contents: yield* lowerMessages(flattened.request),
|
||||
safetySettings: options.safetySettings,
|
||||
serviceTier: options.serviceTier,
|
||||
systemInstruction:
|
||||
@@ -491,7 +492,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
|
||||
tools: hasTools
|
||||
? [
|
||||
{
|
||||
functionDeclarations: request.tools.map((tool) =>
|
||||
functionDeclarations: flattened.tools.map((tool) =>
|
||||
lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),
|
||||
),
|
||||
},
|
||||
|
||||
@@ -414,10 +414,11 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
|
||||
tool: (name) => ({ type: "function" as const, function: { name } }),
|
||||
})
|
||||
: undefined
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
return {
|
||||
model: request.model.id,
|
||||
messages: yield* lowerMessages(request),
|
||||
tools: request.tools.length > 0 ? request.tools.map(lowerTool) : undefined,
|
||||
messages: yield* lowerMessages(flattened.request),
|
||||
tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined,
|
||||
tool_choice: toolChoice,
|
||||
stream: true as const,
|
||||
max_tokens: request.generation?.maxTokens,
|
||||
|
||||
@@ -189,6 +189,7 @@ export const InputItem = Schema.Union([
|
||||
id: Schema.optionalKey(Schema.String),
|
||||
call_id: Schema.String,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
arguments: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
@@ -315,6 +316,7 @@ export const StreamItem = Schema.StructWithRest(
|
||||
id: Schema.optional(Schema.String),
|
||||
call_id: Schema.optional(Schema.String),
|
||||
name: Schema.optional(Schema.String),
|
||||
namespace: Schema.optional(Schema.String),
|
||||
arguments: Schema.optional(Schema.String),
|
||||
encrypted_content: optionalNull(Schema.String),
|
||||
}),
|
||||
@@ -488,6 +490,7 @@ const lowerToolCall = (part: ToolCallPart, providerMetadataKey: string): OpenRes
|
||||
...(id === undefined ? {} : { id }),
|
||||
call_id: part.id,
|
||||
name: part.name,
|
||||
namespace: part.namespace,
|
||||
arguments: ProviderShared.encodeJson(part.input),
|
||||
}
|
||||
}
|
||||
@@ -807,14 +810,15 @@ export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAd
|
||||
request: LLMRequest,
|
||||
adapter: ProviderAdapter,
|
||||
) {
|
||||
const projected = ProviderShared.flattenToolRequest(request)
|
||||
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
|
||||
return {
|
||||
...(yield* lowerConversation(request, adapter)),
|
||||
...(yield* lowerConversation(projected.request, adapter)),
|
||||
...lowerGeneration(request),
|
||||
tools:
|
||||
request.tools.length === 0
|
||||
projected.tools.length === 0
|
||||
? undefined
|
||||
: yield* Effect.forEach(request.tools, (tool) =>
|
||||
: yield* Effect.forEach(projected.tools, (tool) =>
|
||||
lowerTool(
|
||||
adapter.name,
|
||||
tool,
|
||||
@@ -1094,11 +1098,20 @@ const onOutputItemAdded = (state: ParserState, event: NormalizedEvent): StepResu
|
||||
tools: ToolStream.start(state.tools, item.id, {
|
||||
id: item.call_id,
|
||||
name: item.name ?? "",
|
||||
namespace: item.namespace,
|
||||
input: item.arguments ?? "",
|
||||
providerMetadata: metadata,
|
||||
}),
|
||||
},
|
||||
[...events, LLMEvent.toolInputStart({ id: item.call_id, name: item.name ?? "", providerMetadata: metadata })],
|
||||
[
|
||||
...events,
|
||||
LLMEvent.toolInputStart({
|
||||
id: item.call_id,
|
||||
name: item.name ?? "",
|
||||
namespace: item.namespace,
|
||||
providerMetadata: metadata,
|
||||
}),
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1217,7 +1230,12 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
|
||||
const registered = state.tools[item.id] !== undefined
|
||||
const tools = registered
|
||||
? state.tools
|
||||
: ToolStream.start(state.tools, item.id, { id: item.call_id, name: item.name, providerMetadata: metadata })
|
||||
: ToolStream.start(state.tools, item.id, {
|
||||
id: item.call_id,
|
||||
name: item.name,
|
||||
namespace: item.namespace,
|
||||
providerMetadata: metadata,
|
||||
})
|
||||
const result =
|
||||
item.arguments === undefined
|
||||
? yield* ToolStream.finish(state.id, tools, item.id)
|
||||
@@ -1228,7 +1246,15 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
|
||||
const resultEvents =
|
||||
registered || finished.length === 0
|
||||
? finished
|
||||
: [LLMEvent.toolInputStart({ id: item.call_id, name: item.name, providerMetadata: metadata }), ...finished]
|
||||
: [
|
||||
LLMEvent.toolInputStart({
|
||||
id: item.call_id,
|
||||
name: item.name,
|
||||
namespace: item.namespace,
|
||||
providerMetadata: metadata,
|
||||
}),
|
||||
...finished,
|
||||
]
|
||||
const lifecycle = resultEvents.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
|
||||
events.push(...resultEvents)
|
||||
return [
|
||||
|
||||
@@ -736,6 +736,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||
)
|
||||
const generation = request.generation
|
||||
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
const provider = String(request.model.provider)
|
||||
const baseURL = request.model.route.endpoint.baseURL
|
||||
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
|
||||
@@ -748,16 +749,16 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||
const zaiToolStream =
|
||||
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
|
||||
const hasHistory = hasToolHistory(request.messages)
|
||||
const hasActiveTools = request.tools.length > 0
|
||||
const hasActiveTools = flattened.tools.length > 0
|
||||
return {
|
||||
model: request.model.id,
|
||||
messages: yield* lowerMessages(request, options),
|
||||
messages: yield* lowerMessages(flattened.request, options),
|
||||
tools:
|
||||
request.tools.length === 0
|
||||
flattened.tools.length === 0
|
||||
? hasHistory
|
||||
? []
|
||||
: undefined
|
||||
: request.tools.map((tool) =>
|
||||
: flattened.tools.map((tool) =>
|
||||
lowerTool(
|
||||
tool,
|
||||
ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Auth } from "../route/auth.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { Protocol } from "../route/protocol.js"
|
||||
import { HttpTransport } from "../route/transport/index.js"
|
||||
import type { LLMRequest, JsonSchema, ToolDefinition } from "../schema/index.js"
|
||||
import type { LLMRequest, JsonSchema, ToolDefinition, ToolEntry } from "../schema/index.js"
|
||||
import { OpenResponses } from "./open-responses.js"
|
||||
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
|
||||
import { OpenAIImage } from "./utils/openai-image.js"
|
||||
@@ -75,7 +75,18 @@ const OpenAIResponsesHostedToolItem = Schema.Union([
|
||||
),
|
||||
])
|
||||
|
||||
const OpenAIResponsesTools = Schema.Union([OpenResponses.Tool, OpenAIResponsesImageGenerationTool])
|
||||
const OpenAIResponsesNamespace = Schema.Struct({
|
||||
type: Schema.tag("namespace"),
|
||||
name: Schema.String,
|
||||
description: Schema.String,
|
||||
tools: Schema.Array(OpenResponses.Tool),
|
||||
})
|
||||
|
||||
const OpenAIResponsesTools = Schema.Union([
|
||||
OpenResponses.Tool,
|
||||
OpenAIResponsesNamespace,
|
||||
OpenAIResponsesImageGenerationTool,
|
||||
])
|
||||
|
||||
const OpenAIResponsesToolChoice = Schema.Union([
|
||||
OpenResponses.ToolChoice,
|
||||
@@ -128,13 +139,33 @@ const lowerTool = Effect.fn("OpenAIResponses.lowerTool")(function* (tool: ToolDe
|
||||
return yield* OpenResponses.lowerTool(NAME, tool, inputSchema)
|
||||
})
|
||||
|
||||
const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>, tools: ReadonlyArray<ToolDefinition>) =>
|
||||
// Native namespaces hold only function tools, so deeper levels flatten into
|
||||
// the leaf names the same way non-native protocols flatten the whole tree.
|
||||
const lowerToolEntry = Effect.fn("OpenAIResponses.lowerToolEntry")(function* (
|
||||
tool: ToolEntry,
|
||||
compatibility: Parameters<typeof ToolSchemaProjection.modelCompatibility>[1],
|
||||
) {
|
||||
if (tool.type === "tool")
|
||||
return yield* lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, compatibility))
|
||||
// OpenAI requires a namespace description; fall back to a generic one so a
|
||||
// missing description never blocks the request.
|
||||
return {
|
||||
type: "namespace" as const,
|
||||
name: tool.name,
|
||||
description: tool.description ?? `Tools in the ${tool.name} namespace.`,
|
||||
tools: yield* Effect.forEach(ProviderShared.flattenTools(tool.tools), (leaf) =>
|
||||
OpenResponses.lowerTool(NAME, leaf, ToolSchemaProjection.modelCompatibility(leaf.inputSchema, compatibility)),
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>, tools: ReadonlyArray<ToolEntry>) =>
|
||||
ProviderShared.matchToolChoice(NAME, toolChoice, {
|
||||
auto: () => "auto" as const,
|
||||
none: () => "none" as const,
|
||||
required: () => "required" as const,
|
||||
tool: (name) =>
|
||||
tools.some((tool) => tool.name === name && nativeImageTool(tool) !== undefined)
|
||||
tools.some((tool) => tool.type === "tool" && tool.name === name && nativeImageTool(tool) !== undefined)
|
||||
? ({ type: "image_generation" } as const)
|
||||
: { type: "function" as const, name },
|
||||
})
|
||||
@@ -153,9 +184,7 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
|
||||
tools:
|
||||
request.tools.length === 0
|
||||
? undefined
|
||||
: yield* Effect.forEach(request.tools, (tool) =>
|
||||
lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),
|
||||
),
|
||||
: yield* Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, toolSchemaCompatibility)),
|
||||
tool_choice:
|
||||
OpenResponses.allowedToolChoice(request) ??
|
||||
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined),
|
||||
|
||||
@@ -9,11 +9,14 @@ import {
|
||||
UnsupportedOperationError,
|
||||
AIError,
|
||||
HttpContext,
|
||||
LLMRequest,
|
||||
Message,
|
||||
ToolDefinition,
|
||||
type ContentPart,
|
||||
type LLMRequest,
|
||||
type MediaPart,
|
||||
type ProviderID,
|
||||
type TextPart,
|
||||
type ToolEntry,
|
||||
type ToolResultPart,
|
||||
} from "../schema/index.js"
|
||||
import { isRecord } from "../utils/record.js"
|
||||
@@ -46,6 +49,7 @@ export const promptCacheKey = (request: LLMRequest): string | undefined => {
|
||||
export interface ToolAccumulator {
|
||||
readonly id: string
|
||||
readonly name: string
|
||||
readonly namespace?: string
|
||||
readonly input: string
|
||||
}
|
||||
|
||||
@@ -279,6 +283,38 @@ export const unsupportedOperation = (input: {
|
||||
}),
|
||||
})
|
||||
|
||||
/**
|
||||
* Lower namespaces to flat definitions for protocols without a native
|
||||
* namespace construct. Leaf names join their namespace path with `_` because
|
||||
* `.` is not broadly accepted in provider tool names.
|
||||
*/
|
||||
export const flattenTools = (tools: ReadonlyArray<ToolEntry>, path: ReadonlyArray<string> = []) => {
|
||||
const flat = tools.flatMap((tool): ReadonlyArray<ToolDefinition> => {
|
||||
if (tool.type === "namespace") return flattenTools(tool.tools, [...path, tool.name])
|
||||
if (path.length === 0) return [tool]
|
||||
return [new ToolDefinition({ ...tool, name: [...path, tool.name].join("_") })]
|
||||
})
|
||||
return [...new Map(flat.map((tool) => [tool.name, tool])).values()]
|
||||
}
|
||||
|
||||
export const flattenToolRequest = (request: LLMRequest) => {
|
||||
const messages = request.messages.map((message) => {
|
||||
const content = message.content.map((part) => {
|
||||
if ((part.type !== "tool-call" && part.type !== "tool-result") || part.namespace === undefined) return part
|
||||
return { ...part, name: `${part.namespace}_${part.name}`, namespace: undefined }
|
||||
})
|
||||
return content.every((part, index) => part === message.content[index])
|
||||
? message
|
||||
: new Message({ ...message, content })
|
||||
})
|
||||
return {
|
||||
tools: flattenTools(request.tools),
|
||||
request: messages.every((message, index) => message === request.messages[index])
|
||||
? request
|
||||
: LLMRequest.update(request, { messages }),
|
||||
}
|
||||
}
|
||||
|
||||
export const imageResponse = Effect.fn("ProviderShared.imageResponse")(function* (
|
||||
route: string,
|
||||
name: string,
|
||||
|
||||
@@ -55,6 +55,7 @@ const inputStart = (tool: PendingTool) =>
|
||||
LLMEvent.toolInputStart({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
namespace: tool.namespace,
|
||||
providerExecuted: tool.providerExecuted ? true : undefined,
|
||||
providerMetadata: tool.providerMetadata,
|
||||
})
|
||||
@@ -63,6 +64,7 @@ const inputDelta = (tool: PendingTool, text: string) =>
|
||||
LLMEvent.toolInputDelta({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
namespace: tool.namespace,
|
||||
text,
|
||||
input: Option.getOrElse(parsePartialInput(tool.input), () => ({})),
|
||||
})
|
||||
@@ -85,6 +87,7 @@ const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
||||
LLMEvent.toolCall({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
namespace: tool.namespace,
|
||||
input,
|
||||
providerExecuted: tool.providerExecuted ? true : undefined,
|
||||
providerMetadata: tool.providerMetadata,
|
||||
@@ -94,7 +97,12 @@ const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
||||
}
|
||||
|
||||
const finishEvents = (tool: PendingTool, event: ToolCall): ReadonlyArray<LLMEvent> => [
|
||||
LLMEvent.toolInputEnd({ id: tool.id, name: tool.name, providerMetadata: tool.providerMetadata }),
|
||||
LLMEvent.toolInputEnd({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
namespace: tool.namespace,
|
||||
providerMetadata: tool.providerMetadata,
|
||||
}),
|
||||
event,
|
||||
]
|
||||
|
||||
@@ -150,6 +158,7 @@ export const appendOrStart = <K extends StreamKey>(
|
||||
const tool = {
|
||||
id,
|
||||
name,
|
||||
namespace: current?.namespace,
|
||||
input: `${current?.input ?? ""}${delta.text}`,
|
||||
providerExecuted: current?.providerExecuted,
|
||||
providerMetadata: current?.providerMetadata,
|
||||
@@ -159,6 +168,17 @@ export const appendOrStart = <K extends StreamKey>(
|
||||
return appendTool(tools, key, tool, delta.text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Append argument text to a started tool. Returns `undefined` when no tool is
|
||||
* open under `key`, for protocols that ignore deltas without a matching block.
|
||||
*/
|
||||
export const append = <K extends StreamKey>(tools: State<K>, key: K, text: string): AppendOutcome<K> | undefined => {
|
||||
const current = tools[key]
|
||||
if (!current) return undefined
|
||||
if (text.length === 0) return { tools, tool: current, events: [] }
|
||||
return appendTool(tools, key, { ...current, input: `${current.input}${text}` }, text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Append argument text to a tool that must already have been started. This keeps
|
||||
* protocols honest when their stream grammar promises a start event before any
|
||||
@@ -170,12 +190,7 @@ export const appendExisting = <K extends StreamKey>(
|
||||
key: K,
|
||||
text: string,
|
||||
missingToolMessage: string,
|
||||
): AppendOutcome<K> | AIError => {
|
||||
const current = tools[key]
|
||||
if (!current) return eventError(route, missingToolMessage)
|
||||
if (text.length === 0) return { tools, tool: current, events: [] }
|
||||
return appendTool(tools, key, { ...current, input: `${current.input}${text}` }, text)
|
||||
}
|
||||
): AppendOutcome<K> | AIError => append(tools, key, text) ?? eventError(route, missingToolMessage)
|
||||
|
||||
/**
|
||||
* Finalize one pending tool call: parse the accumulated raw JSON, remove it
|
||||
|
||||
@@ -487,10 +487,14 @@ export function make<Body, Prepared, Frame, Event, State>(
|
||||
}
|
||||
|
||||
const prepareRequest = (request: LLMRequest) => {
|
||||
const original = applyCachePolicy(resolveRequestOptions(request))
|
||||
const original = resolveRequestOptions(request)
|
||||
const sanitized = LLMRequest.update(original, sanitizeSurrogates({ ...LLMRequest.input(original), model: undefined }))
|
||||
const tools = [...new Map(sanitized.tools.map((tool) => [tool.name, tool])).values()]
|
||||
const resolved = tools.length === sanitized.tools.length ? sanitized : LLMRequest.update(sanitized, { tools })
|
||||
// Deduplicate per sibling level; a tool and a namespace may share a name.
|
||||
const dedupe = (tools: LLMRequest["tools"]): LLMRequest["tools"] =>
|
||||
[...new Map(tools.map((tool) => [`${tool.type}:${tool.name}`, tool])).values()].map((tool) =>
|
||||
tool.type === "tool" ? tool : { ...tool, tools: dedupe(tool.tools) },
|
||||
)
|
||||
const resolved = applyCachePolicy(LLMRequest.update(sanitized, { tools: dedupe(sanitized.tools) }))
|
||||
const headers = resolved.model.route.headers?.({ request: resolved })
|
||||
return headers === undefined
|
||||
? resolved
|
||||
|
||||
@@ -155,6 +155,7 @@ export const ToolInputStart = Schema.Struct({
|
||||
type: Schema.tag("tool-input-start"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
providerExecuted: Schema.optional(Schema.Boolean),
|
||||
providerMetadata: Schema.optional(ProviderMetadata),
|
||||
}).annotate({ identifier: "LLM.Event.ToolInputStart" })
|
||||
@@ -164,6 +165,7 @@ export const ToolInputDelta = Schema.Struct({
|
||||
type: Schema.tag("tool-input-delta"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
text: Schema.String,
|
||||
/** Best-effort parse of all input fragments received through this delta. */
|
||||
input: Schema.optional(Schema.Unknown),
|
||||
@@ -174,6 +176,7 @@ export const ToolInputEnd = Schema.Struct({
|
||||
type: Schema.tag("tool-input-end"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
providerMetadata: Schema.optional(ProviderMetadata),
|
||||
}).annotate({ identifier: "LLM.Event.ToolInputEnd" })
|
||||
export type ToolInputEnd = Schema.Schema.Type<typeof ToolInputEnd>
|
||||
@@ -183,6 +186,7 @@ export const ToolInputError = Schema.Struct({
|
||||
type: Schema.tag("tool-input-error"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
raw: Schema.String,
|
||||
}).annotate({ identifier: "LLM.Event.ToolInputError" })
|
||||
export type ToolInputError = Schema.Schema.Type<typeof ToolInputError>
|
||||
@@ -191,6 +195,7 @@ export const ToolCall = Schema.Struct({
|
||||
type: Schema.tag("tool-call"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
input: Schema.Unknown,
|
||||
providerExecuted: Schema.optional(Schema.Boolean),
|
||||
providerMetadata: Schema.optional(ProviderMetadata),
|
||||
@@ -201,6 +206,7 @@ export const ToolResult = Schema.Struct({
|
||||
type: Schema.tag("tool-result"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
result: ToolResultValue,
|
||||
output: Schema.optional(ToolOutput),
|
||||
providerExecuted: Schema.optional(Schema.Boolean),
|
||||
@@ -212,6 +218,7 @@ export const ToolError = Schema.Struct({
|
||||
type: Schema.tag("tool-error"),
|
||||
id: ToolCallID,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
message: Schema.String,
|
||||
error: Schema.optional(Schema.Defect()),
|
||||
providerMetadata: Schema.optional(ProviderMetadata),
|
||||
@@ -385,6 +392,7 @@ interface ContentAssembly {
|
||||
|
||||
interface ToolInputAssembly {
|
||||
readonly name: string
|
||||
readonly namespace?: string
|
||||
readonly text: string
|
||||
readonly providerMetadata?: ProviderMetadata
|
||||
}
|
||||
@@ -522,12 +530,17 @@ const reduceToolInputStart = (state: ResponseState, event: ToolInputStart): Resp
|
||||
...state,
|
||||
toolInputs: {
|
||||
...state.toolInputs,
|
||||
[event.id]: { name: event.name, text: "", providerMetadata: event.providerMetadata },
|
||||
[event.id]: {
|
||||
name: event.name,
|
||||
namespace: event.namespace,
|
||||
text: "",
|
||||
providerMetadata: event.providerMetadata,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const reduceToolInputDelta = (state: ResponseState, event: ToolInputDelta): ResponseState => {
|
||||
const current = state.toolInputs[event.id] ?? { name: event.name, text: "" }
|
||||
const current = state.toolInputs[event.id] ?? { name: event.name, namespace: event.namespace, text: "" }
|
||||
return {
|
||||
...state,
|
||||
toolInputs: { ...state.toolInputs, [event.id]: { ...current, text: current.text + event.text } },
|
||||
@@ -535,7 +548,7 @@ const reduceToolInputDelta = (state: ResponseState, event: ToolInputDelta): Resp
|
||||
}
|
||||
|
||||
const reduceToolInputEnd = (state: ResponseState, event: ToolInputEnd): ResponseState => {
|
||||
const current = state.toolInputs[event.id] ?? { name: event.name, text: "" }
|
||||
const current = state.toolInputs[event.id] ?? { name: event.name, namespace: event.namespace, text: "" }
|
||||
return {
|
||||
...state,
|
||||
toolInputs: {
|
||||
@@ -543,6 +556,7 @@ const reduceToolInputEnd = (state: ResponseState, event: ToolInputEnd): Response
|
||||
[event.id]: {
|
||||
...current,
|
||||
name: event.name,
|
||||
namespace: event.namespace,
|
||||
providerMetadata: event.providerMetadata ?? current.providerMetadata,
|
||||
},
|
||||
},
|
||||
@@ -553,6 +567,7 @@ const toolCallContent = (event: ToolCall): ContentPart =>
|
||||
ToolCallPart.make({
|
||||
id: event.id,
|
||||
name: event.name,
|
||||
namespace: event.namespace,
|
||||
input: event.input,
|
||||
...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),
|
||||
...(event.providerMetadata === undefined ? {} : { providerMetadata: event.providerMetadata }),
|
||||
@@ -562,6 +577,7 @@ const toolResultContent = (event: ToolResult): ContentPart =>
|
||||
ToolResultPart.make({
|
||||
id: event.id,
|
||||
name: event.name,
|
||||
namespace: event.namespace,
|
||||
result: event.result,
|
||||
...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),
|
||||
...(event.providerMetadata === undefined ? {} : { providerMetadata: event.providerMetadata }),
|
||||
|
||||
@@ -135,6 +135,7 @@ export const ToolCallPart = Object.assign(
|
||||
type: Schema.Literal("tool-call"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
input: Schema.Unknown,
|
||||
providerExecuted: Schema.optional(Schema.Boolean),
|
||||
cache: Schema.optional(CacheHint),
|
||||
@@ -152,6 +153,7 @@ export const ToolResultPart = Object.assign(
|
||||
type: Schema.Literal("tool-result"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
namespace: Schema.optional(Schema.String),
|
||||
result: ToolResultValue,
|
||||
providerExecuted: Schema.optional(Schema.Boolean),
|
||||
cache: Schema.optional(CacheHint),
|
||||
@@ -168,6 +170,7 @@ export const ToolResultPart = Object.assign(
|
||||
type: "tool-result",
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
namespace: input.namespace,
|
||||
result: ToolResultValue.make(input.result, input.resultType),
|
||||
providerExecuted: input.providerExecuted,
|
||||
cache: input.cache,
|
||||
@@ -266,7 +269,7 @@ export namespace Message {
|
||||
make({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] })
|
||||
}
|
||||
|
||||
export class ToolDefinition extends Schema.Class<ToolDefinition>("LLM.ToolDefinition")({
|
||||
const toolDefinitionFields = {
|
||||
name: Schema.String,
|
||||
description: Schema.String,
|
||||
inputSchema: JsonSchema,
|
||||
@@ -274,15 +277,71 @@ export class ToolDefinition extends Schema.Class<ToolDefinition>("LLM.ToolDefini
|
||||
cache: Schema.optional(CacheHint),
|
||||
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
}) {}
|
||||
}
|
||||
|
||||
export type ToolDefinitionInput = Schema.Struct.Type<typeof toolDefinitionFields>
|
||||
|
||||
export class ToolDefinition extends Schema.Class<ToolDefinition>("LLM.ToolDefinition")({
|
||||
type: Schema.Literal("tool"),
|
||||
...toolDefinitionFields,
|
||||
}) {
|
||||
constructor(input: ToolDefinitionInput) {
|
||||
super({ ...input, type: "tool" })
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ToolDefinition {
|
||||
export type Input = ToolDefinition | ConstructorParameters<typeof ToolDefinition>[0]
|
||||
export type Input = ToolDefinition | ToolDefinitionInput
|
||||
|
||||
/** Normalize tool definition input into the canonical `ToolDefinition` class. */
|
||||
export const make = (input: Input) => (input instanceof ToolDefinition ? input : new ToolDefinition(input))
|
||||
}
|
||||
|
||||
export type ToolNamespace = {
|
||||
readonly type: "namespace"
|
||||
readonly name: string
|
||||
readonly description?: string
|
||||
readonly tools: ReadonlyArray<ToolEntry>
|
||||
}
|
||||
|
||||
export type ToolNamespaceInput = Omit<ToolNamespace, "type" | "tools"> & {
|
||||
readonly tools: ReadonlyArray<ToolEntryInput>
|
||||
}
|
||||
export type ToolNamespaceEntryInput = ToolNamespaceInput & { readonly type: "namespace" }
|
||||
|
||||
export const ToolNamespace: Schema.Codec<ToolNamespace> & {
|
||||
readonly make: (input: ToolNamespace | ToolNamespaceInput) => ToolNamespace
|
||||
} = Object.assign(
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("namespace"),
|
||||
name: Schema.String,
|
||||
description: Schema.optional(Schema.UndefinedOr(Schema.String)),
|
||||
tools: Schema.Array(Schema.suspend((): Schema.Codec<ToolEntry> => ToolEntry)),
|
||||
}).annotate({ identifier: "LLM.ToolNamespace" }),
|
||||
{
|
||||
make: (input: ToolNamespace | ToolNamespaceInput): ToolNamespace => ({
|
||||
...input,
|
||||
type: "namespace",
|
||||
tools: input.tools.map(ToolEntry.make),
|
||||
}),
|
||||
},
|
||||
)
|
||||
|
||||
export type ToolEntry = ToolDefinition | ToolNamespace
|
||||
export type ToolEntryInput = ToolDefinition.Input | ToolNamespaceEntryInput
|
||||
export const ToolEntry: Schema.Codec<ToolEntry> & {
|
||||
readonly make: (input: ToolEntryInput) => ToolEntry
|
||||
} = Object.assign(
|
||||
Schema.Union([ToolDefinition, ToolNamespace]).pipe(
|
||||
Schema.toTaggedUnion("type"),
|
||||
Schema.annotate({ identifier: "LLM.ToolEntry" }),
|
||||
),
|
||||
{
|
||||
make: (input: ToolEntryInput): ToolEntry =>
|
||||
"type" in input && input.type === "namespace" ? ToolNamespace.make(input) : ToolDefinition.make(input),
|
||||
},
|
||||
)
|
||||
|
||||
export class ToolChoice extends Schema.Class<ToolChoice>("LLM.ToolChoice")({
|
||||
type: Schema.Literals(["auto", "none", "required", "tool"]),
|
||||
name: Schema.optional(Schema.String),
|
||||
@@ -312,7 +371,7 @@ const requestSchema = Schema.Struct({
|
||||
model: LanguageModelSchema,
|
||||
system: Schema.Array(SystemPart),
|
||||
messages: Schema.Array(Message),
|
||||
tools: Schema.Array(ToolDefinition),
|
||||
tools: Schema.Array(ToolEntry),
|
||||
toolChoice: Schema.optional(ToolChoice),
|
||||
generation: Schema.optional(GenerationOptions),
|
||||
providerOptions: Schema.optional(ProviderOptions),
|
||||
|
||||
@@ -37,7 +37,13 @@ function missingToolResults(calls: Iterable<ToolCallPart>) {
|
||||
return new Message({
|
||||
role: "tool",
|
||||
content: [...calls].map((call) =>
|
||||
ToolResultPart.make({ id: call.id, name: call.name, result: MISSING_TOOL_RESULT, resultType: "error" }),
|
||||
ToolResultPart.make({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
namespace: call.namespace,
|
||||
result: MISSING_TOOL_RESULT,
|
||||
resultType: "error",
|
||||
}),
|
||||
),
|
||||
})
|
||||
}
|
||||
@@ -47,7 +53,7 @@ function normalizeToolMessage(message: Message, pending: Map<string, ToolCallPar
|
||||
if (part.type !== "tool-result" || part.providerExecuted === true) return part
|
||||
const call = pending.get(part.id)
|
||||
if (call) pending.delete(part.id)
|
||||
return normalizeToolResult(part, call?.name ?? part.name)
|
||||
return normalizeToolResult(part, call)
|
||||
})
|
||||
if (content.length === 0) return undefined
|
||||
if (content.every((part, index) => part === message.content[index])) return message
|
||||
@@ -61,8 +67,11 @@ function normalizeToolMessage(message: Message, pending: Map<string, ToolCallPar
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeToolResult(part: ToolResultPart, name: string): ToolResultPart {
|
||||
const named = part.name === name ? part : { ...part, name }
|
||||
function normalizeToolResult(part: ToolResultPart, call: ToolCallPart | undefined): ToolResultPart {
|
||||
const named =
|
||||
call === undefined || (part.name === call.name && part.namespace === call.namespace)
|
||||
? part
|
||||
: { ...part, name: call.name, namespace: call.namespace }
|
||||
if (named.result.type === "text" && named.result.value === "")
|
||||
return { ...named, result: { type: "text", value: EMPTY_TOOL_OUTPUT } }
|
||||
if (named.result.type === "error" && named.result.value === "")
|
||||
|
||||
@@ -21,10 +21,11 @@ export interface DispatchResult extends ToolSettlement {
|
||||
|
||||
/** Execute one canonical tool call without owning provider IO or continuation. */
|
||||
export const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect<DispatchResult> => {
|
||||
const tool = tools[call.name]
|
||||
if (!tool) return Effect.succeed(result(call, { type: "error", value: `Unknown tool: ${call.name}` }))
|
||||
const name = call.namespace === undefined ? call.name : `${call.namespace}.${call.name}`
|
||||
const tool = tools[name]
|
||||
if (!tool) return Effect.succeed(result(call, { type: "error", value: `Unknown tool: ${name}` }))
|
||||
if (!tool.execute)
|
||||
return Effect.succeed(result(call, { type: "error", value: `Tool has no execute handler: ${call.name}` }))
|
||||
return Effect.succeed(result(call, { type: "error", value: `Tool has no execute handler: ${name}` }))
|
||||
|
||||
return decodeAndExecute(tool, call).pipe(
|
||||
Effect.map((value) => result(call, value)),
|
||||
@@ -38,7 +39,11 @@ const decodeAndExecute = (tool: AnyTool, call: ToolCallPart): Effect.Effect<Tool
|
||||
tool._decode(call.input).pipe(
|
||||
Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
|
||||
Effect.flatMap((decoded) =>
|
||||
tool.execute!(decoded, { id: call.id, name: call.name }).pipe(
|
||||
tool.execute!(decoded, {
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
namespace: call.namespace,
|
||||
}).pipe(
|
||||
Effect.flatMap((value) =>
|
||||
tool._encode(value).pipe(
|
||||
Effect.mapError(
|
||||
@@ -71,6 +76,7 @@ const result = (call: ToolCallPart, value: ToolResultValueType | ToolSettlement,
|
||||
LLMEvent.toolError({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
namespace: call.namespace,
|
||||
message: String(settlement.result.value),
|
||||
error,
|
||||
providerMetadata: call.providerMetadata,
|
||||
@@ -78,6 +84,7 @@ const result = (call: ToolCallPart, value: ToolResultValueType | ToolSettlement,
|
||||
LLMEvent.toolResult({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
namespace: call.namespace,
|
||||
result: settlement.result,
|
||||
providerMetadata: call.providerMetadata,
|
||||
}),
|
||||
@@ -86,6 +93,7 @@ const result = (call: ToolCallPart, value: ToolResultValueType | ToolSettlement,
|
||||
LLMEvent.toolResult({
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
namespace: call.namespace,
|
||||
result: settlement.result,
|
||||
output: settlement.output,
|
||||
providerMetadata: call.providerMetadata,
|
||||
|
||||
@@ -16,6 +16,7 @@ export type ToolSchema<T> = Schema.Codec<T, any, never, never>
|
||||
export interface ToolExecuteContext {
|
||||
readonly id: ToolCallPart["id"]
|
||||
readonly name: ToolCallPart["name"]
|
||||
readonly namespace?: ToolCallPart["namespace"]
|
||||
}
|
||||
|
||||
export type ToolExecute<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = (
|
||||
|
||||
@@ -215,6 +215,35 @@ describe("applyCachePolicy", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("deduplicates tools before counting cache hints", () =>
|
||||
Effect.gen(function* () {
|
||||
const manual = new CacheHint({ type: "ephemeral" })
|
||||
const duplicate = (description: string) => ({
|
||||
name: "lookup",
|
||||
description,
|
||||
inputSchema: { type: "object" },
|
||||
cache: manual,
|
||||
})
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model: anthropicModel,
|
||||
tools: [
|
||||
duplicate("first"),
|
||||
duplicate("second"),
|
||||
duplicate("third"),
|
||||
duplicate("fourth"),
|
||||
{ name: "lookup", description: "final", inputSchema: { type: "object" } },
|
||||
],
|
||||
cache: { tools: true },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
expect.objectContaining({ name: "lookup", description: "final", cache_control: { type: "ephemeral" } }),
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("auto policy preserves manual CacheHints on other parts", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
@@ -281,6 +310,30 @@ describe("applyCachePolicy", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
test("marks the final leaf inside a tool namespace", () => {
|
||||
const request = LLM.request({
|
||||
model: anthropicModel,
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
tools: [
|
||||
{ name: "lookup", description: "lookup", inputSchema: {} },
|
||||
{ name: "orders", description: "orders", inputSchema: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
cache: { tools: true },
|
||||
})
|
||||
const applied = applyCachePolicy(request)
|
||||
const namespace = applied.tools[0]
|
||||
|
||||
expect(namespace?.type).toBe("namespace")
|
||||
if (namespace?.type !== "namespace") throw new Error("Expected namespace")
|
||||
expect(namespace.tools[0]).not.toHaveProperty("cache")
|
||||
expect(namespace.tools[1]).toHaveProperty("cache", { type: "ephemeral" })
|
||||
})
|
||||
|
||||
it.effect("ttlSeconds in the policy flows through to wire markers", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Effect, Ref, Schema } from "effect"
|
||||
import { HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { LLM, LLMRequest, Message, ToolCallPart, ToolDefinition, mergeProviderOptions } from "../src/index.js"
|
||||
import { AnthropicMessages, OpenAIChat } from "../src/protocols.js"
|
||||
import {
|
||||
LLM,
|
||||
LLMRequest,
|
||||
Message,
|
||||
ToolCallPart,
|
||||
ToolDefinition,
|
||||
ToolNamespace,
|
||||
mergeProviderOptions,
|
||||
} from "../src/index.js"
|
||||
import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../src/protocols.js"
|
||||
import { Auth, LLMClient } from "../src/route.js"
|
||||
import { compileRequest } from "../src/route/client.js"
|
||||
import { it } from "./lib/effect.js"
|
||||
@@ -106,6 +114,58 @@ describe("request option precedence", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("deduplicates tools within each namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model: OpenAIResponses.route.model({ id: "gpt-5.4" }),
|
||||
tools: [
|
||||
ToolDefinition.make({ name: "crm", description: "Top-level CRM tool", inputSchema: {} }),
|
||||
ToolNamespace.make({
|
||||
name: "crm",
|
||||
description: "CRM tools",
|
||||
tools: [
|
||||
ToolDefinition.make({ name: "lookup", description: "old", inputSchema: {} }),
|
||||
ToolDefinition.make({ name: "search", description: "search", inputSchema: {} }),
|
||||
ToolDefinition.make({ name: "lookup", description: "new", inputSchema: {} }),
|
||||
],
|
||||
}),
|
||||
ToolNamespace.make({
|
||||
name: "support",
|
||||
description: "Support tools",
|
||||
tools: [ToolDefinition.make({ name: "lookup", description: "support", inputSchema: {} })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
{
|
||||
type: "function",
|
||||
name: "crm",
|
||||
description: "Top-level CRM tool",
|
||||
parameters: {},
|
||||
strict: false,
|
||||
},
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "CRM tools",
|
||||
tools: [
|
||||
{ type: "function", name: "lookup", description: "new", parameters: {}, strict: false },
|
||||
{ type: "function", name: "search", description: "search", parameters: {}, strict: false },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "namespace",
|
||||
name: "support",
|
||||
description: "Support tools",
|
||||
tools: [{ type: "function", name: "lookup", description: "support", parameters: {}, strict: false }],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("normalizes tool history before protocol lowering", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { CacheHint, LLM, LLMResponse } from "../src/index.js"
|
||||
import { Schema } from "effect"
|
||||
import { CacheHint, LLM, LLMResponse, ToolEntry, ToolNamespace } from "../src/index.js"
|
||||
import * as OpenAIChat from "../src/protocols/openai-chat.js"
|
||||
import * as OpenAIResponses from "../src/protocols/openai-responses.js"
|
||||
import {
|
||||
@@ -17,6 +18,52 @@ const chatRoute = OpenAIChat.route
|
||||
const responsesRoute = OpenAIResponses.route
|
||||
|
||||
describe("llm constructors", () => {
|
||||
test("normalizes recursive tool namespaces", () => {
|
||||
const request = LLM.request({
|
||||
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: responsesRoute }),
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [
|
||||
{ name: "lookup", description: "Look up a customer", inputSchema: { type: "object" } },
|
||||
{
|
||||
type: "namespace",
|
||||
name: "orders",
|
||||
tools: [{ name: "list", description: "List orders", inputSchema: { type: "object" } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(request.tools[0]).toEqual({
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [
|
||||
expect.objectContaining({ type: "tool", name: "lookup" }),
|
||||
{
|
||||
type: "namespace",
|
||||
name: "orders",
|
||||
description: undefined,
|
||||
tools: [expect.objectContaining({ type: "tool", name: "list" })],
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(request.tools[0]).toEqual(
|
||||
ToolNamespace.make({
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: request.tools[0]!.type === "namespace" ? request.tools[0].tools : [],
|
||||
}),
|
||||
)
|
||||
expect(Schema.decodeUnknownSync(ToolEntry)(Schema.encodeUnknownSync(ToolEntry)(request.tools[0]))).toEqual(
|
||||
request.tools[0],
|
||||
)
|
||||
})
|
||||
|
||||
test("builds canonical schema classes from ergonomic input", () => {
|
||||
const request = LLM.request({
|
||||
id: "req_1",
|
||||
|
||||
@@ -713,9 +713,10 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("ignores late tool deltas after contentBlockStop", () =>
|
||||
it.effect("ignores tool deltas without an open tool block", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
["contentBlockDelta", { contentBlockIndex: 5, delta: { toolUse: { input: "{}" } } }],
|
||||
[
|
||||
"contentBlockStart",
|
||||
{
|
||||
@@ -745,27 +746,6 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects tool deltas without contentBlockStart", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(baseRequest).pipe(
|
||||
Effect.provide(
|
||||
fixedBytes(
|
||||
eventStreamBody(
|
||||
["contentBlockDelta", { contentBlockIndex: 0, delta: { toolUse: { input: "{}" } } }],
|
||||
["messageStop", { stopReason: "tool_use" }],
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error).toMatchObject({
|
||||
reason: { _tag: "InvalidProviderOutput" },
|
||||
message: "Bedrock Converse tool delta is missing its tool call",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers incomplete tool input at finalization", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect } from "bun:test"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { LLM, LLMRequest, Message } from "../../src/index.js"
|
||||
import { LLM, LLMRequest, Message, ToolDefinition } from "../../src/index.js"
|
||||
import { LLMClient, Route } from "../../src/route/client.js"
|
||||
import { Auth } from "../../src/route/auth.js"
|
||||
import { Endpoint } from "../../src/route/endpoint.js"
|
||||
@@ -134,7 +134,12 @@ for (const model of [
|
||||
[
|
||||
LLMRequest.update(request, {
|
||||
tools: [
|
||||
{ name: "unsupported", description: "Generation only", inputSchema: {}, native: { unsupported: {} } },
|
||||
ToolDefinition.make({
|
||||
name: "unsupported",
|
||||
description: "Generation only",
|
||||
inputSchema: {},
|
||||
native: { unsupported: {} },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
"InvalidRequest",
|
||||
|
||||
@@ -326,7 +326,6 @@ describe("Open Responses basic-item lifecycles", () => {
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("mints an id for a done-only tool that never had one", () =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* collect(
|
||||
@@ -357,9 +356,16 @@ describe("Open Responses basic-item lifecycles", () => {
|
||||
const events = yield* collect({ type: "response.output_item.done", item }, completed)
|
||||
const providerMetadata = { "openai-compatible": { itemId: "fc_1" } }
|
||||
expect(events.filter((event) => event.type.startsWith("tool-"))).toEqual([
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata },
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata },
|
||||
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" }, providerMetadata },
|
||||
{ type: "tool-input-start", id: "call_1", name: "lookup", namespace: undefined, providerMetadata },
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup", namespace: undefined, providerMetadata },
|
||||
{
|
||||
type: "tool-call",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
namespace: undefined,
|
||||
input: { query: "weather" },
|
||||
providerMetadata,
|
||||
},
|
||||
])
|
||||
expect(events.filter(LLMEvent.is.finish)).toEqual([
|
||||
{
|
||||
|
||||
@@ -171,6 +171,66 @@ describe("Open Responses-compatible route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("flattens tool namespaces", () =>
|
||||
Effect.gen(function* () {
|
||||
const model = configure({ apiKey: "test-key", baseURL: "https://responses.example.test/v1" }).model(
|
||||
"example-model",
|
||||
)
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "acme",
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "billing",
|
||||
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup billing", inputSchema: {} })],
|
||||
},
|
||||
ToolDefinition.make({ name: "users", description: "Lookup users", inputSchema: {} }),
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
{
|
||||
type: "function",
|
||||
name: "acme_billing_lookup",
|
||||
description: "Lookup billing",
|
||||
parameters: {},
|
||||
strict: false,
|
||||
},
|
||||
{ type: "function", name: "acme_users", description: "Lookup users", parameters: {}, strict: false },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("flattens tool namespaces in history", () =>
|
||||
Effect.gen(function* () {
|
||||
const model = configure({ apiKey: "test-key", baseURL: "https://responses.example.test/v1" }).model(
|
||||
"example-model",
|
||||
)
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [
|
||||
Message.assistant({ type: "tool-call", id: "call_1", name: "lookup", namespace: "crm", input: {} }),
|
||||
Message.tool({ id: "call_1", name: "lookup", namespace: "crm", result: "done", resultType: "text" }),
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.input).toEqual([
|
||||
{ type: "function_call", call_id: "call_1", name: "crm_lookup", namespace: undefined, arguments: "{}" },
|
||||
{ type: "function_call_output", call_id: "call_1", output: "done" },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("lowers canonical parallel tool control", () =>
|
||||
Effect.gen(function* () {
|
||||
const model = configure({
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
LanguageModel,
|
||||
ToolCallPart,
|
||||
ToolDefinition,
|
||||
ToolNamespace,
|
||||
ToolResultPart,
|
||||
TransportError,
|
||||
Usage,
|
||||
@@ -143,6 +144,94 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("lowers tool namespaces without flattening leaf names", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
prompt: "Find a customer and their orders.",
|
||||
tools: [
|
||||
ToolNamespace.make({
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [
|
||||
ToolDefinition.make({ name: "lookup", description: "Look up a customer", inputSchema: {} }),
|
||||
ToolDefinition.make({ name: "orders", description: "List customer orders", inputSchema: {} }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [
|
||||
{ type: "function", name: "lookup", description: "Look up a customer", parameters: {}, strict: false },
|
||||
{ type: "function", name: "orders", description: "List customer orders", parameters: {}, strict: false },
|
||||
],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("flattens nested levels within a native tool namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "orders",
|
||||
description: "Order management",
|
||||
tools: [ToolDefinition.make({ name: "list", description: "List orders", inputSchema: {} })],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
description: "Customer management",
|
||||
tools: [{ type: "function", name: "orders_list", description: "List orders", parameters: {}, strict: false }],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("defaults tool namespace descriptions", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
tools: [
|
||||
{
|
||||
type: "namespace",
|
||||
name: "crm",
|
||||
tools: [ToolDefinition.make({ name: "lookup", description: "Look up a customer", inputSchema: {} })],
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prepared.body.tools).toEqual([
|
||||
expect.objectContaining({ type: "namespace", name: "crm", description: "Tools in the crm namespace." }),
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects invalid hosted image generation options locally", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* compileRequest(
|
||||
@@ -2130,6 +2219,71 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("preserves tool namespaces through streaming and history replay", () =>
|
||||
Effect.gen(function* () {
|
||||
const item = {
|
||||
type: "function_call",
|
||||
id: "fc_1",
|
||||
call_id: "call_1",
|
||||
namespace: "crm",
|
||||
name: "lookup",
|
||||
arguments: "",
|
||||
}
|
||||
const response = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(
|
||||
sseEvents(
|
||||
{ type: "response.output_item.added", output_index: 0, item },
|
||||
{
|
||||
type: "response.function_call_arguments.delta",
|
||||
output_index: 0,
|
||||
item_id: "fc_1",
|
||||
delta: '{"id":"123"}',
|
||||
},
|
||||
{
|
||||
type: "response.output_item.done",
|
||||
output_index: 0,
|
||||
item: { ...item, arguments: '{"id":"123"}' },
|
||||
},
|
||||
{ type: "response.completed", response: { id: "resp_1" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
const toolEvents = response.events.filter((event) => event.type.startsWith("tool-"))
|
||||
expect(toolEvents).toEqual([
|
||||
expect.objectContaining({ type: "tool-input-start", name: "lookup", namespace: "crm" }),
|
||||
expect.objectContaining({ type: "tool-input-delta", name: "lookup", namespace: "crm" }),
|
||||
expect.objectContaining({ type: "tool-input-end", name: "lookup", namespace: "crm" }),
|
||||
expect.objectContaining({ type: "tool-call", name: "lookup", namespace: "crm", input: { id: "123" } }),
|
||||
])
|
||||
expect(response.message.content).toEqual([
|
||||
expect.objectContaining({ type: "tool-call", name: "lookup", namespace: "crm", input: { id: "123" } }),
|
||||
])
|
||||
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [
|
||||
response.message,
|
||||
Message.tool({ id: "call_1", name: "lookup", namespace: "crm", result: { customer: "Ada" } }),
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.input).toEqual([
|
||||
{
|
||||
type: "function_call",
|
||||
id: "fc_1",
|
||||
call_id: "call_1",
|
||||
namespace: "crm",
|
||||
name: "lookup",
|
||||
arguments: '{"id":"123"}',
|
||||
},
|
||||
{ type: "function_call_output", call_id: "call_1", output: '{"customer":"Ada"}' },
|
||||
])
|
||||
}),
|
||||
)
|
||||
it.effect("routes reasoning summary events by output index", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* LLMClient.generate(request).pipe(
|
||||
|
||||
@@ -15,13 +15,7 @@ describe("tool history normalization", () => {
|
||||
Message.assistant(toolCall("trailing")),
|
||||
])
|
||||
|
||||
expect(normalized.map((message) => message.role)).toEqual([
|
||||
"assistant",
|
||||
"tool",
|
||||
"tool",
|
||||
"user",
|
||||
"assistant",
|
||||
])
|
||||
expect(normalized.map((message) => message.role)).toEqual(["assistant", "tool", "tool", "user", "assistant"])
|
||||
expect(normalized[1]?.content[0]).toMatchObject({ type: "tool-result", id: "first", name: "first" })
|
||||
expect(normalized[2]?.content).toEqual([
|
||||
{ type: "tool-result", id: "second", name: "second", result: { type: "error", value: "Tool result missing" } },
|
||||
@@ -74,4 +68,13 @@ describe("tool history normalization", () => {
|
||||
|
||||
expect(normalizeToolHistory([orphan, hosted])).toEqual([orphan, hosted])
|
||||
})
|
||||
|
||||
test("uses a matching call as the complete tool identity", () => {
|
||||
const normalized = normalizeToolHistory([
|
||||
Message.assistant(ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })),
|
||||
Message.tool(ToolResultPart.make({ id: "call_1", name: "wrong", namespace: "stale", result: "done" })),
|
||||
])
|
||||
|
||||
expect(normalized[1]?.content[0]).toMatchObject({ name: "lookup", namespace: undefined })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
LLMResponse,
|
||||
ToolCallPart,
|
||||
ToolChoice,
|
||||
ToolOutput,
|
||||
toDefinitions,
|
||||
@@ -36,6 +37,27 @@ const baseRequest = LLM.request({
|
||||
})
|
||||
const weatherFailureCause = new Error("weather lookup denied")
|
||||
|
||||
test("dispatches namespaced calls by qualified identity", async () => {
|
||||
let context: ToolExecuteContext | undefined
|
||||
const lookup = Tool.make({
|
||||
description: "Look up a customer.",
|
||||
parameters: Schema.Struct({}),
|
||||
success: Schema.String,
|
||||
execute: (_, value) => {
|
||||
context = value
|
||||
return Effect.succeed("customer")
|
||||
},
|
||||
})
|
||||
const call = ToolCallPart.make({ id: "call_1", namespace: "crm", name: "lookup", input: {} })
|
||||
const result = await Effect.runPromise(
|
||||
ToolRuntime.dispatch({ "crm.lookup": lookup, lookup: schema_only_weather }, call),
|
||||
)
|
||||
|
||||
expect(result.result).toEqual({ type: "text", value: "customer" })
|
||||
expect(context).toEqual({ id: "call_1", namespace: "crm", name: "lookup" })
|
||||
expect(result.events).toEqual([expect.objectContaining({ type: "tool-result", namespace: "crm", name: "lookup" })])
|
||||
})
|
||||
|
||||
const get_weather = Tool.make({
|
||||
description: "Get current weather for a city.",
|
||||
parameters: Schema.Struct({ city: Schema.String }),
|
||||
|
||||
@@ -134,7 +134,7 @@ for (const viewport of [
|
||||
await expect(page).toHaveURL(pending.url)
|
||||
await expect(pending.message).toHaveAttribute("data-timeline-part-id", `${pending.messageID}:text:0`)
|
||||
await expect(pending.shimmer).toHaveAttribute("data-active", "true")
|
||||
await expect(pending.title).toHaveText("New session")
|
||||
await expect(pending.title).toHaveText("Session")
|
||||
await expect(editor).toHaveText(followUp)
|
||||
expect(mock.calls).toEqual(["worktree"])
|
||||
|
||||
@@ -238,7 +238,7 @@ for (const direction of ["ltr", "rtl"]) {
|
||||
!frame.message ||
|
||||
!frame.spinner ||
|
||||
frame.draft !== followUp ||
|
||||
!["New session", "Created workspace session"].includes(frame.title ?? ""),
|
||||
!["Session", "Created workspace session"].includes(frame.title ?? ""),
|
||||
),
|
||||
).toEqual([])
|
||||
const after = await title.boundingBox()
|
||||
@@ -598,7 +598,7 @@ async function submitPending(page: Page, mock: Awaited<ReturnType<typeof openDra
|
||||
const shimmer = preparing.getByRole("status").locator('[data-component="text-shimmer"]')
|
||||
const title = preparing.getByRole("heading", { level: 1 })
|
||||
await expect(preparing).toBeVisible()
|
||||
await expect(title).toHaveText("New session")
|
||||
await expect(title).toHaveText("Session")
|
||||
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
|
||||
await expect(page.locator('[data-action="composer-submit"]')).toBeDisabled()
|
||||
await expect(preparing.locator('[data-component="user-message"]')).toHaveCount(1)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
|
||||
const directory = "/tmp/settings-padding"
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: "proj_settings_padding",
|
||||
canonical: directory,
|
||||
name: "Settings padding",
|
||||
vcs: "git",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.route("https://api.github.com/repos/anomalyco/opencode/contributors?*", (route) =>
|
||||
route.fulfill({ json: [] }),
|
||||
)
|
||||
await page.goto("/")
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
await expect(page.getByTestId("settings-screen")).toBeFocused()
|
||||
})
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 720, bottom: false },
|
||||
{ width: 900, height: 600, bottom: false },
|
||||
{ width: 780, height: 600, bottom: false },
|
||||
{ width: 390, height: 844, bottom: false },
|
||||
{ width: 390, height: 844, bottom: true },
|
||||
]) {
|
||||
test.describe(`${viewport.width}px, ${viewport.bottom ? "bottom" : "top"} navigation`, () => {
|
||||
test.use({ viewport: { width: 1280, height: 720 }, contextOptions: { reducedMotion: "reduce" } })
|
||||
|
||||
test("every settings page leaves room below its final content", async ({ page }) => {
|
||||
await page.setViewportSize(viewport)
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
const panel = settings.locator(":scope > .settings > .settings-panel:visible")
|
||||
if (viewport.bottom) {
|
||||
const toggle = settings.locator('[data-action="settings-mobile-titlebar-bottom"]')
|
||||
await toggle.locator('[data-slot="switch-control"]').click()
|
||||
await expect(toggle.getByRole("switch")).toBeChecked()
|
||||
}
|
||||
let current = "Preferences"
|
||||
for (const name of [
|
||||
"Preferences",
|
||||
"Appearance",
|
||||
"Notifications",
|
||||
"Shortcuts",
|
||||
"Servers",
|
||||
"Projects",
|
||||
"Worktrees",
|
||||
"Providers",
|
||||
"Models",
|
||||
"Extensions",
|
||||
"Experimental",
|
||||
"About",
|
||||
]) {
|
||||
if (viewport.width >= 816) await settings.getByRole("tab", { name, exact: true }).click()
|
||||
if (viewport.width < 816) {
|
||||
await settings.getByRole("button", { name: current, exact: true }).click()
|
||||
await page.getByRole("menuitemradio", { name, exact: true }).click()
|
||||
}
|
||||
current = name
|
||||
if (name === "About") await expect(panel.getByText("Released under the MIT License")).toBeVisible()
|
||||
if (name !== "About") {
|
||||
await expect(
|
||||
panel.getByRole("heading", { name: name === "Shortcuts" ? "Keyboard shortcuts" : name, exact: true }),
|
||||
).toBeVisible()
|
||||
}
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect
|
||||
.poll(() => panel.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))
|
||||
.toBeLessThanOrEqual(1)
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
panel.evaluate((el) => {
|
||||
const body = el.querySelector(".settings-tab-body, .settings-about-content")!
|
||||
return el.getBoundingClientRect().bottom - body.lastElementChild!.getBoundingClientRect().bottom
|
||||
}),
|
||||
{ message: `${name} bottom clearance` },
|
||||
)
|
||||
.toBeGreaterThanOrEqual(viewport.bottom ? 119.5 : 79.5)
|
||||
await expect
|
||||
.poll(() => page.getByRole("main").evaluate((el) => el.scrollWidth - el.clientWidth))
|
||||
.toBeLessThanOrEqual(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
|
||||
test.use({ contextOptions: { reducedMotion: "reduce" }, colorScheme: "dark" })
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1280, height: 720 },
|
||||
{ width: 900, height: 600 },
|
||||
{ width: 780, height: 600 },
|
||||
{ width: 390, height: 844 },
|
||||
]) {
|
||||
test(`preferences scroll only inside the panel at ${viewport.width}x${viewport.height}`, async ({ page }) => {
|
||||
const directory = "/tmp/settings-scroll"
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: "proj_settings_scroll",
|
||||
canonical: directory,
|
||||
name: "Settings scroll",
|
||||
vcs: "git",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.goto("/")
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
const panel = settings.getByRole("tabpanel")
|
||||
const main = page.getByRole("main")
|
||||
const slider = settings.getByRole("slider", { name: "Timeline detail", exact: true })
|
||||
await expect(settings).toBeFocused()
|
||||
await page.setViewportSize(viewport)
|
||||
await expect(slider).toHaveAccessibleDescription(/Choose how much activity appears in the timeline/)
|
||||
await expect.poll(() => main.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1)
|
||||
|
||||
// Wheel over the outer gutter must not move the entire settings screen.
|
||||
await main.hover({ position: { x: 1, y: 200 } })
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect.poll(() => panel.evaluate((el) => el.scrollTop)).toBeGreaterThan(0)
|
||||
await expect(main).toHaveJSProperty("scrollTop", 0)
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeInViewport()
|
||||
|
||||
await slider.scrollIntoViewIfNeeded()
|
||||
await slider.click()
|
||||
await page.keyboard.press("Home")
|
||||
await expect(slider).toHaveValue("0")
|
||||
await page.keyboard.press("ArrowRight")
|
||||
await expect(slider).toHaveValue("1")
|
||||
await expect(slider).toBeFocused()
|
||||
|
||||
await settings.getByRole("button", { name: "Advanced", exact: true }).click()
|
||||
await expect(
|
||||
settings.getByRole("group", { name: "Set placement and details for each activity category.", exact: true }),
|
||||
).toBeVisible()
|
||||
await panel.hover()
|
||||
await page.mouse.wheel(0, 10000)
|
||||
await expect
|
||||
.poll(() => panel.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))
|
||||
.toBeLessThanOrEqual(1)
|
||||
await expect(main).toHaveJSProperty("scrollTop", 0)
|
||||
await expect.poll(() => main.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1)
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeInViewport()
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { onMount } from "solid-js"
|
||||
import { onCleanup, onMount } from "solid-js"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import type { ComposerAttachment, ComposerPrompt } from "../types"
|
||||
|
||||
@@ -78,6 +78,7 @@ export type ComposerAttachmentConfig = {
|
||||
onError: (error: unknown) => void
|
||||
readClipboardImage?: () => Promise<File | null>
|
||||
getPathForFile?: (file: File) => string
|
||||
onDragCancel?: (callback: () => void) => () => void
|
||||
store?: (file: File) => Promise<{ id: string; url: string }>
|
||||
}
|
||||
|
||||
@@ -90,6 +91,9 @@ export function createComposerAttachments(
|
||||
setDraggingType: (type: "image" | "@mention" | null) => void
|
||||
},
|
||||
) {
|
||||
const clearDrag = () => {
|
||||
input.setDraggingType(null)
|
||||
}
|
||||
const capture = () => {
|
||||
const prompt = input.capture()
|
||||
const editor = input.editor()
|
||||
@@ -178,7 +182,7 @@ export function createComposerAttachments(
|
||||
const handleDrop = async (event: DragEvent) => {
|
||||
if (input.isDialogActive()) return
|
||||
event.preventDefault()
|
||||
input.setDraggingType(null)
|
||||
clearDrag()
|
||||
const plainText = event.dataTransfer?.getData("text/plain")
|
||||
if (plainText?.startsWith("file:")) {
|
||||
const path = plainText.slice("file:".length)
|
||||
@@ -191,6 +195,8 @@ export function createComposerAttachments(
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
const cancel = input.onDragCancel?.(clearDrag)
|
||||
if (cancel) onCleanup(cancel)
|
||||
makeEventListener(document, "dragover", (event) => {
|
||||
if (input.isDialogActive()) return
|
||||
event.preventDefault()
|
||||
@@ -198,7 +204,10 @@ export function createComposerAttachments(
|
||||
else if (event.dataTransfer?.types.includes("text/plain")) input.setDraggingType("@mention")
|
||||
})
|
||||
makeEventListener(document, "dragleave", (event) => {
|
||||
if (!input.isDialogActive() && !event.relatedTarget) input.setDraggingType(null)
|
||||
if (!input.isDialogActive() && !event.relatedTarget) clearDrag()
|
||||
})
|
||||
makeEventListener(document, "keydown", (event) => {
|
||||
if (event.key === "Escape") clearDrag()
|
||||
})
|
||||
makeEventListener(document, "drop", handleDrop)
|
||||
})
|
||||
|
||||
@@ -118,7 +118,6 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
class="group/composer relative min-h-[96px] w-full overflow-clip rounded-xl bg-v2-background-bg-base"
|
||||
classList={{
|
||||
"shadow-[var(--v2-elevation-raised)]": !props.borderUnderlay,
|
||||
"border border-v2-icon-icon-info border-dashed": state.drag === "active",
|
||||
}}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
@@ -129,12 +128,6 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
onDragLeave={props.controller.onDragLeave}
|
||||
onDrop={props.controller.onDrop}
|
||||
>
|
||||
<Show when={state.drag === "active"}>
|
||||
<div class="pointer-events-none absolute inset-0 z-20 grid place-items-center rounded-xl bg-v2-background-bg-base/90 text-v2-text-text-base">
|
||||
{i18n.t("ui.promptInput.dropFiles")}
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={state.mode === "normal"}>
|
||||
<ComposerAttachments
|
||||
attachments={props.controller.attachments()}
|
||||
|
||||
@@ -42,9 +42,14 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
|
||||
const interaction = createComposerEditorState(prompt.mode.current())
|
||||
createEffect(
|
||||
on(adapter.ready, (ready) => {
|
||||
if (ready) interaction[1]("mode", prompt.mode.current())
|
||||
}),
|
||||
on(
|
||||
() => (adapter.ready() ? prompt.mode.current() : undefined),
|
||||
(mode) => {
|
||||
if (!mode) return
|
||||
// Project external draft changes without another mode write clearing restored retry metadata.
|
||||
interaction[1](mode === "shell" ? { mode, popover: { type: "closed" } } : { mode })
|
||||
},
|
||||
),
|
||||
)
|
||||
const mode = () => interaction[0].mode
|
||||
const history = createComposerHistory()
|
||||
@@ -346,6 +351,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
}),
|
||||
readClipboardImage: platform.readClipboardImage,
|
||||
getPathForFile: platform.getPathForFile,
|
||||
onDragCancel: platform.onDragCancel,
|
||||
store: platform.draftStore?.putBlob,
|
||||
},
|
||||
view: {
|
||||
|
||||
@@ -319,6 +319,69 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes session-dropzone-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes session-dropzone-content-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px) scale(0.96);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes session-dropzone-upload-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px) scale(0.92);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes session-dropzone-stripes-drift {
|
||||
to {
|
||||
background-position: 33.941px 0;
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="session-dropzone"][data-visible="true"] {
|
||||
animation: session-dropzone-enter 200ms cubic-bezier(0.215, 0.61, 0.355, 1);
|
||||
}
|
||||
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-content"] {
|
||||
animation: session-dropzone-content-enter 200ms cubic-bezier(0.215, 0.61, 0.355, 1);
|
||||
}
|
||||
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-upload"] {
|
||||
animation: session-dropzone-upload-enter 240ms cubic-bezier(0.215, 0.61, 0.355, 1);
|
||||
}
|
||||
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-stripes"] {
|
||||
animation: session-dropzone-stripes-drift 3s linear infinite;
|
||||
}
|
||||
|
||||
[data-component="session-dropzone"] {
|
||||
--session-dropzone-wash: 4%;
|
||||
--session-dropzone-stripe: 7%;
|
||||
--session-dropzone-card: var(--v2-background-bg-base);
|
||||
}
|
||||
|
||||
[data-color-scheme="dark"] [data-component="session-dropzone"] {
|
||||
--session-dropzone-wash: 6%;
|
||||
--session-dropzone-stripe: 14%;
|
||||
--session-dropzone-card: var(--v2-background-bg-layer-01);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-component="session-dropzone"][data-visible="true"],
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-content"],
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-upload"],
|
||||
[data-component="session-dropzone"][data-visible="true"] [data-slot="session-dropzone-stripes"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="home-projects-scroll"] {
|
||||
timeline-scope: --home-projects-scroll;
|
||||
}
|
||||
|
||||
@@ -59,6 +59,9 @@ type PlatformBase = {
|
||||
/** Resolve the native source path for a desktop File. */
|
||||
getPathForFile?(file: File): string
|
||||
|
||||
/** Observe native drag cancellation that does not reach the renderer event loop. */
|
||||
onDragCancel?(callback: () => void): () => void
|
||||
|
||||
/** Open a native save file dialog and write content to the selected path (desktop only) */
|
||||
saveFile?(opts: SaveFilePickerOptions, content: string): Promise<boolean>
|
||||
|
||||
|
||||
@@ -4,16 +4,14 @@ import { useComposerState } from "@/composer/persistence"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import type { SessionModel } from "../model"
|
||||
|
||||
export function createActiveComposerAdapter(input: {
|
||||
session: SessionModel
|
||||
sessionID: string
|
||||
controls: Accessor<ComposerControls>
|
||||
submitted: () => void
|
||||
setEditor: (element: HTMLDivElement) => void
|
||||
}) {
|
||||
const id = input.session.identity.params.id
|
||||
if (!id) throw new Error("Active Composer requires a Session ID")
|
||||
const id = input.sessionID
|
||||
|
||||
const prompt = useComposerState()
|
||||
prompt.current()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { createEffect, createMemo, on, type Accessor } from "solid-js"
|
||||
import type { ComposerControls } from "@/composer/adapter"
|
||||
import { setCursorPosition } from "@/composer/editor/dom"
|
||||
import { createComposerModel } from "@/composer/model"
|
||||
import { useSettings } from "@/settings/model"
|
||||
import { createActiveComposerAdapter } from "./adapter"
|
||||
import { createSessionQueue } from "./queue"
|
||||
import { createSessionComposerRegionController } from "./session-composer-region-controller"
|
||||
|
||||
export function createSessionComposerController(input: {
|
||||
sessionID: string
|
||||
controls: Accessor<ComposerControls>
|
||||
dock: Parameters<typeof createSessionComposerRegionController>[0]
|
||||
}) {
|
||||
const settings = useSettings()
|
||||
const region = createSessionComposerRegionController(input.dock)
|
||||
let editor: HTMLDivElement | undefined
|
||||
const adapter = createActiveComposerAdapter({
|
||||
sessionID: input.sessionID,
|
||||
controls: input.controls,
|
||||
submitted: region.onResponseSubmit,
|
||||
setEditor: (element) => {
|
||||
editor = element
|
||||
region.setPromptRef(element)
|
||||
},
|
||||
})
|
||||
const queue = createSessionQueue({
|
||||
sessionID: input.sessionID,
|
||||
draft: adapter.state,
|
||||
working: adapter.working,
|
||||
behavior: settings.general.followUpBehavior,
|
||||
restoreFocus: (cursor) => {
|
||||
const target = editor
|
||||
if (!target) return
|
||||
requestAnimationFrame(() => {
|
||||
target.focus()
|
||||
setCursorPosition(target, cursor)
|
||||
})
|
||||
},
|
||||
})
|
||||
const composer = createComposerModel(adapter, { queue })
|
||||
const editable = createMemo(() => region.showComposer() && !region.child())
|
||||
// Requests hide the view without disposing its draft or queue edit.
|
||||
createEffect(on(editable, () => composer.onDragLeave()))
|
||||
|
||||
return {
|
||||
region,
|
||||
queue,
|
||||
composer,
|
||||
drop: {
|
||||
active: () => editable() && composer.state.drag === "active",
|
||||
input: () => composer.model.selection.current()?.capabilities.input,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type SessionComposerController = ReturnType<typeof createSessionComposerController>
|
||||
@@ -4,7 +4,6 @@ import { useMutation } from "@tanstack/solid-query"
|
||||
import type { SessionInboxInfo } from "@opencode-ai/client/promise"
|
||||
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||
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"
|
||||
@@ -30,7 +29,7 @@ export function createSessionQueue(input: {
|
||||
draft: ComposerStateTarget
|
||||
working: Accessor<boolean>
|
||||
behavior: Accessor<ComposerDelivery>
|
||||
composer: Accessor<ComposerModel | undefined>
|
||||
restoreFocus: (cursor: number) => void
|
||||
}) {
|
||||
const data = useData()
|
||||
const server = useServerSDK()
|
||||
@@ -159,9 +158,9 @@ export function createSessionQueue(input: {
|
||||
},
|
||||
})
|
||||
const text = queuedPromptText(item)
|
||||
input.composer()?.dispatch({ type: "mode.normal" })
|
||||
input.draft.mode.set("normal")
|
||||
input.draft.set([{ type: "text", content: text, start: 0, end: text.length }], text.length)
|
||||
input.composer()?.restoreFocus(text.length)
|
||||
input.restoreFocus(text.length)
|
||||
return true
|
||||
}
|
||||
const cancelEdit = () => {
|
||||
@@ -170,10 +169,10 @@ export function createSessionQueue(input: {
|
||||
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.mode.set(editing.stash.mode)
|
||||
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)
|
||||
input.restoreFocus(editing.stash.cursor)
|
||||
}
|
||||
const confirmEdit = (delivery: ComposerDelivery) => {
|
||||
const editing = state.editing
|
||||
|
||||
@@ -4,9 +4,8 @@ import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||
import { isScrollKeyTarget, scrollKey, scrollKeyOwner } from "@opencode-ai/ui/scroll-view"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { useNavigate } from "@solidjs/router"
|
||||
import { createEffect, on, onMount } from "solid-js"
|
||||
import { createEffect, createMemo, on, onMount, type Accessor } from "solid-js"
|
||||
import { Composer } from "@/composer/composer"
|
||||
import { createComposerModel, type ComposerModel } from "@/composer/model"
|
||||
import { useComposerState } from "@/composer/persistence"
|
||||
import { createComposerControls } from "@/composer/selection"
|
||||
import { setCursorPosition } from "@/composer/editor/dom"
|
||||
@@ -25,18 +24,16 @@ import { restorePromptModel, syncPromptModel, syncSessionModel } from "../sessio
|
||||
import type { SessionTimelineInteraction } from "../timeline/interaction"
|
||||
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 { createSessionComposerController, type SessionComposerController } from "./controller"
|
||||
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
|
||||
screen: SessionScreenLayout
|
||||
timeline: SessionTimelineInteraction
|
||||
visible: Accessor<boolean>
|
||||
}) {
|
||||
const command = useCommand()
|
||||
const dialog = useDialog()
|
||||
@@ -180,7 +177,30 @@ export function createActiveSessionRegion(input: {
|
||||
},
|
||||
])
|
||||
|
||||
const dock = {
|
||||
state,
|
||||
parentID: input.session.data.parentID,
|
||||
centered: input.screen.centered,
|
||||
onResponseSubmit: input.timeline.actions.resume,
|
||||
openParent,
|
||||
setPromptRef: (element: HTMLDivElement) => {
|
||||
promptRef = element
|
||||
},
|
||||
setDockRef: input.timeline.view.setDockRef,
|
||||
}
|
||||
const active = createMemo(
|
||||
on(
|
||||
() => (input.visible() ? input.session.identity.sessionID() : undefined),
|
||||
(sessionID) => (sessionID ? createSessionComposerController({ sessionID, controls, dock }) : undefined),
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
active,
|
||||
drop: {
|
||||
active: () => active()?.drop.active() ?? false,
|
||||
input: () => active()?.drop.input(),
|
||||
},
|
||||
actions: {
|
||||
timeline: {
|
||||
get revert() {
|
||||
@@ -190,76 +210,25 @@ export function createActiveSessionRegion(input: {
|
||||
openAttachment,
|
||||
} satisfies SessionUserActions,
|
||||
},
|
||||
region: {
|
||||
centered: input.screen.centered,
|
||||
openParent,
|
||||
prompt,
|
||||
setDockRef: input.timeline.view.setDockRef,
|
||||
setPromptRef: (element: HTMLDivElement) => {
|
||||
promptRef = element
|
||||
},
|
||||
state,
|
||||
},
|
||||
input: {
|
||||
controls,
|
||||
setPromptRef: (element: HTMLDivElement) => {
|
||||
promptRef = element
|
||||
},
|
||||
},
|
||||
submitted: () => input.timeline.actions.resume(),
|
||||
requests: state,
|
||||
workspaceMoveEligible: () => true,
|
||||
}
|
||||
}
|
||||
|
||||
export type ActiveSessionRegionModel = ReturnType<typeof createActiveSessionRegion>
|
||||
|
||||
export function ActiveSessionComposerRegion(props: {
|
||||
model: ActiveSessionRegionModel
|
||||
session: SessionModel
|
||||
onResponseSubmit: () => void
|
||||
}) {
|
||||
const settings = useSettings()
|
||||
const region = createSessionComposerRegionController({
|
||||
state: props.model.region.state,
|
||||
parentID: props.session.data.parentID,
|
||||
centered: props.model.region.centered,
|
||||
onResponseSubmit: props.onResponseSubmit,
|
||||
openParent: props.model.region.openParent,
|
||||
setPromptRef: props.model.region.setPromptRef,
|
||||
setDockRef: props.model.region.setDockRef,
|
||||
})
|
||||
const adapter = createActiveComposerAdapter({
|
||||
session: props.session,
|
||||
controls: props.model.input.controls,
|
||||
submitted: props.model.submitted,
|
||||
setEditor: props.model.input.setPromptRef,
|
||||
})
|
||||
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 })
|
||||
export function ActiveSessionComposerRegion(props: { model: SessionComposerController }) {
|
||||
return (
|
||||
<SessionComposerRegion
|
||||
controller={region}
|
||||
controller={props.model.region}
|
||||
composer={
|
||||
<div class="relative">
|
||||
<SessionQueuePanel queue={queue} />
|
||||
<SessionQueuePanel queue={props.model.queue} />
|
||||
<div class="relative z-10">
|
||||
<Composer model={composer} borderUnderlay />
|
||||
<Composer model={props.model.composer} borderUnderlay />
|
||||
</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
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@ import {
|
||||
} from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { ResizeHandle } from "@opencode-ai/ui/resize-handle"
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { MessageTimeline, SessionSummaryPanel } from "@/session/timeline/message-timeline"
|
||||
import { useServer } from "@/runtime/server/current"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { projectForSession } from "@/shell/layout/helpers"
|
||||
import type { SessionModel } from "@/session/model"
|
||||
import { SESSION_PANEL_WIDTH_MIN } from "@/session/session-panel-width"
|
||||
@@ -39,6 +41,7 @@ const SessionMobileFiles = lazy(async () => {
|
||||
export function SessionScreen(props: { session: SessionModel }) {
|
||||
const session = props.session
|
||||
const server = useServer()
|
||||
const language = useLanguage()
|
||||
const detailsProject = createMemo(() => {
|
||||
const info = session.data.info()
|
||||
return info ? projectForSession(info, server.ctx.sync.data.project) : undefined
|
||||
@@ -60,6 +63,7 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
const [elements, setElements] = createStore<{
|
||||
side?: HTMLDivElement
|
||||
bottomTerminal?: HTMLDivElement
|
||||
dropzone?: HTMLDivElement
|
||||
}>({})
|
||||
const sideVisible = createMemo(() => isDesktop() && screen.side.layout().visible)
|
||||
const sideTerminalVisible = createMemo(() => isDesktop() && screen.terminal.side() && screen.terminal.open())
|
||||
@@ -134,7 +138,20 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
session,
|
||||
screen,
|
||||
timeline,
|
||||
visible: conversationVisible,
|
||||
})
|
||||
const dropLabel = createMemo(() => {
|
||||
const input = composer.drop.input()
|
||||
if (!input?.image && !input?.pdf) return language.t("ui.promptInput.dropFiles")
|
||||
if (!input.pdf) return language.t("ui.promptInput.dropFiles.image")
|
||||
if (!input.image) return language.t("ui.promptInput.dropFiles.pdf")
|
||||
return language.t("ui.promptInput.dropFiles.imagePdf")
|
||||
})
|
||||
const dropPresence = createAnimatedPresence(
|
||||
() => (composer.drop.active() ? dropLabel() : undefined),
|
||||
() => elements.dropzone ?? null,
|
||||
session.layout.tabKey,
|
||||
)
|
||||
|
||||
useUsageExceededDialogs()
|
||||
|
||||
@@ -176,7 +193,7 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
review.mobile.setTab("changes")
|
||||
session.layout.view().terminal.close()
|
||||
}}
|
||||
backgroundTasks={composer.region.state.background.tasks()}
|
||||
backgroundTasks={composer.requests.background.tasks()}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
@@ -198,6 +215,63 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
|
||||
const sessionPanelContent = () => (
|
||||
<>
|
||||
<div
|
||||
data-slot="session-dropzone-blur"
|
||||
data-visible={composer.drop.active()}
|
||||
class="pointer-events-none absolute inset-0 z-[79] rounded-[inherit] opacity-[0.001] backdrop-blur-[1.5px] transition-opacity duration-200 ease-[cubic-bezier(0.215,0.61,0.355,1)] will-change-[opacity,backdrop-filter] data-[visible=true]:opacity-100 motion-reduce:transition-none"
|
||||
style={{
|
||||
"-webkit-mask-image":
|
||||
"linear-gradient(to right, transparent 0%, black 25%, black 75%, transparent 100%), linear-gradient(to bottom, transparent 0%, black 28%, black 72%, transparent 100%)",
|
||||
"-webkit-mask-composite": "source-in",
|
||||
"mask-image":
|
||||
"linear-gradient(to right, transparent 0%, black 25%, black 75%, transparent 100%), linear-gradient(to bottom, transparent 0%, black 28%, black 72%, transparent 100%)",
|
||||
"mask-composite": "intersect",
|
||||
}}
|
||||
/>
|
||||
<Show when={dropPresence.present()}>
|
||||
<div
|
||||
ref={(element) => setElements("dropzone", element)}
|
||||
data-component="session-dropzone"
|
||||
data-visible={composer.drop.active()}
|
||||
class="pointer-events-none absolute inset-0 z-[80] grid place-items-center overflow-hidden rounded-[inherit] bg-[color-mix(in_srgb,var(--v2-text-text-base)_var(--session-dropzone-wash),transparent)] opacity-100 transition-opacity duration-200 ease-[cubic-bezier(0.215,0.61,0.355,1)] data-[visible=false]:opacity-0 motion-reduce:transition-none"
|
||||
>
|
||||
<div class="absolute inset-0 bg-v2-background-bg-base/25" />
|
||||
<div
|
||||
class="absolute inset-y-0 left-1/2 w-full -translate-x-1/2 md:max-w-200 2xl:max-w-[1000px]"
|
||||
style={{
|
||||
"-webkit-mask-image": "linear-gradient(to right, transparent 0%, black 12%, black 88%, transparent 100%)",
|
||||
"mask-image": "linear-gradient(to right, transparent 0%, black 12%, black 88%, transparent 100%)",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
data-slot="session-dropzone-stripes"
|
||||
class="absolute inset-0 opacity-60"
|
||||
style={{
|
||||
background:
|
||||
"repeating-linear-gradient(135deg, transparent 0px, transparent 12px, color-mix(in srgb, var(--v2-text-text-base) var(--session-dropzone-stripe), transparent) 12px, color-mix(in srgb, var(--v2-text-text-base) var(--session-dropzone-stripe), transparent) 24px)",
|
||||
"-webkit-mask-image":
|
||||
"radial-gradient(ellipse 59% 40% at center, black 0%, rgba(0,0,0,0.72) 58%, transparent 100%)",
|
||||
"mask-image":
|
||||
"radial-gradient(ellipse 59% 40% at center, black 0%, rgba(0,0,0,0.72) 58%, transparent 100%)",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
data-slot="session-dropzone-content"
|
||||
class="relative flex translate-y-0 flex-col items-center gap-5 opacity-100 transition-[opacity,transform] duration-200 ease-[cubic-bezier(0.215,0.61,0.355,1)] data-[visible=false]:translate-y-1 data-[visible=false]:opacity-0 motion-reduce:transition-none"
|
||||
data-visible={composer.drop.active()}
|
||||
>
|
||||
<div
|
||||
data-slot="session-dropzone-upload"
|
||||
class="flex size-10 items-center justify-center rounded-full bg-[var(--session-dropzone-card)] text-v2-icon-icon-muted shadow-[var(--v2-elevation-floating)]"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<Icon name="arrow-up" size="normal" class="text-v2-icon-icon-muted" />
|
||||
</div>
|
||||
<div class="text-[15px] font-[530] leading-6 text-v2-text-text-base">{dropPresence.value()}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={!isDesktop() && !!session.identity.params.id}>{mobileTabs()}</Show>
|
||||
{/* Surface query errors without suspending session metadata while messages load. */}
|
||||
<Show when={timeline.resource.error}>
|
||||
@@ -235,7 +309,7 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
<MessageTimeline
|
||||
hideHeader={!isDesktop()}
|
||||
session={session}
|
||||
background={composer.region.state.background}
|
||||
background={composer.requests.background}
|
||||
actions={composer.actions.timeline}
|
||||
scroll={timeline.scroll}
|
||||
onResumeScroll={timeline.actions.resume}
|
||||
@@ -263,10 +337,8 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
</Switch>
|
||||
</div>
|
||||
|
||||
<Show when={conversationVisible() ? session.identity.params.id : undefined} keyed>
|
||||
{(_id) => (
|
||||
<ActiveSessionComposerRegion model={composer} session={session} onResponseSubmit={timeline.actions.resume} />
|
||||
)}
|
||||
<Show when={composer.active()} keyed>
|
||||
{(model) => <ActiveSessionComposerRegion model={model} />}
|
||||
</Show>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ export function SessionRouteFrame(props: ParentProps<{ padded?: boolean }>) {
|
||||
export function SessionPanelFrame(props: ParentProps<{ raised?: boolean }>) {
|
||||
return (
|
||||
<div
|
||||
class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-v2-background-bg-base"
|
||||
class="relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-[10px] bg-v2-background-bg-base"
|
||||
classList={{
|
||||
"shadow-[var(--v2-elevation-raised)]": props.raised,
|
||||
}}
|
||||
|
||||
@@ -242,7 +242,7 @@ export function SessionIdentityHeader(props: { sessionID: string; session?: Sess
|
||||
)
|
||||
const title = createMemo(() =>
|
||||
pending()
|
||||
? language.t("command.session.new")
|
||||
? language.t("session.tab.session")
|
||||
: sessionTitle(props.session?.title ?? (parentID() ? undefined : info()?.title)),
|
||||
)
|
||||
const project = createMemo(() => {
|
||||
|
||||
@@ -60,7 +60,6 @@
|
||||
|
||||
.settings-screen .settings-tab-body {
|
||||
padding-inline: 0;
|
||||
padding-bottom: var(--settings-bottom-inset, 0px);
|
||||
}
|
||||
|
||||
.settings-nav {
|
||||
@@ -98,6 +97,7 @@
|
||||
|
||||
.settings-about-content {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
min-height: 462px;
|
||||
@@ -105,7 +105,7 @@
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 24px;
|
||||
padding-block: 80px 32px;
|
||||
padding-block: 80px calc(80px + var(--settings-bottom-inset, 0px));
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
@@ -273,7 +273,7 @@
|
||||
flex-direction: column;
|
||||
gap: 36px;
|
||||
width: 100%;
|
||||
padding: 0 40px 40px;
|
||||
padding: 0 40px calc(80px + var(--settings-bottom-inset, 0px));
|
||||
}
|
||||
|
||||
[data-slot="settings-row-description"] a.settings-link {
|
||||
@@ -1170,7 +1170,7 @@
|
||||
}
|
||||
|
||||
.settings-tab-body.settings-workspaces {
|
||||
padding: 0 20px 24px;
|
||||
padding-inline: 20px;
|
||||
}
|
||||
|
||||
.settings-workspaces-toolbar,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
[data-component="timeline-detail-control"] {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
@@ -105,7 +106,6 @@
|
||||
[data-slot="timeline-detail-advanced"] {
|
||||
margin-top: 4px;
|
||||
padding-top: 8px;
|
||||
border-top: 0.5px solid var(--v2-border-border-base);
|
||||
}
|
||||
|
||||
[data-slot="timeline-detail-advanced"] > [data-slot="collapsible-trigger"] {
|
||||
|
||||
@@ -442,9 +442,11 @@ export function Titlebar(props: {
|
||||
"pt-[max(0px,calc(8px-env(safe-area-inset-top,0px)))]": !bottom() && !windows(),
|
||||
"pb-[max(0px,calc(8px-env(safe-area-inset-bottom,0px)))]": bottom(),
|
||||
"pl-4": macTrafficLights(),
|
||||
// Center the 20px app icon over the sidebar's 16px icon column.
|
||||
"ps-3.5": windows(),
|
||||
}}
|
||||
>
|
||||
<Show when={!mobile() && !props.verticalTabs}>
|
||||
<Show when={!mobile() && (!props.verticalTabs || windows())}>
|
||||
<ChannelIndicator horizontal debugTools={props.debugTools} />
|
||||
</Show>
|
||||
<Show when={windows() || linux()}>
|
||||
@@ -641,7 +643,9 @@ export function Titlebar(props: {
|
||||
data-tauri-drag-region
|
||||
/>
|
||||
</Show>
|
||||
<ChannelIndicator sidebar debugTools={props.debugTools} />
|
||||
<Show when={!windows()}>
|
||||
<ChannelIndicator sidebar debugTools={props.debugTools} />
|
||||
</Show>
|
||||
{homeButton(true)}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { render } from "solid-js/web"
|
||||
import { createComposerAttachments } from "@/composer/attachments/attachments"
|
||||
|
||||
test("clears drag state on platform cancellation", async () => {
|
||||
let cancel = () => {}
|
||||
let subscribed = false
|
||||
let dragging: "image" | "@mention" | null = "image"
|
||||
const dispose = render(() => {
|
||||
createComposerAttachments({
|
||||
capture: () => ({ current: () => [], cursor: () => 0, set: () => {} }),
|
||||
editor: () => undefined,
|
||||
focusEditor: () => {},
|
||||
addPart: () => false,
|
||||
setDraggingType: (type) => (dragging = type),
|
||||
directory: () => "",
|
||||
isDialogActive: () => false,
|
||||
warn: () => {},
|
||||
duplicate: () => {},
|
||||
onError: () => {},
|
||||
onDragCancel: (callback) => {
|
||||
cancel = callback
|
||||
subscribed = true
|
||||
return () => (subscribed = false)
|
||||
},
|
||||
})
|
||||
return null
|
||||
}, document.createElement("div"))
|
||||
await Promise.resolve()
|
||||
|
||||
cancel()
|
||||
|
||||
expect(dragging).toBeNull()
|
||||
dispose()
|
||||
expect(subscribed).toBeFalse()
|
||||
})
|
||||
@@ -1109,6 +1109,8 @@ export async function handler(
|
||||
authInfo = authInfo!
|
||||
|
||||
const cost = centsToMicroCents(totalCostInCent)
|
||||
// Keep period bounds and persisted timestamps on one snapshot when a queued write crosses a reset boundary.
|
||||
const trackedAt = new Date()
|
||||
|
||||
// For hot workspaces, batch balance/usage updates through Redis to avoid
|
||||
// row-level lock contention on BillingTable/UserTable. Returns the amount
|
||||
@@ -1149,7 +1151,7 @@ export async function handler(
|
||||
if (billingSource === "subscription") {
|
||||
const plan = authInfo.billing.subscription!.plan
|
||||
const black = BlackData.getLimits({ plan })
|
||||
const week = getWeekBounds(new Date())
|
||||
const week = getWeekBounds(trackedAt)
|
||||
const rollingWindowSeconds = black.rollingWindow * 3600
|
||||
return [
|
||||
db
|
||||
@@ -1157,11 +1159,17 @@ export async function handler(
|
||||
.set({
|
||||
fixedUsage: sql`
|
||||
CASE
|
||||
WHEN ${SubscriptionTable.timeFixedUpdated} >= ${week.end} THEN ${SubscriptionTable.fixedUsage}
|
||||
WHEN ${SubscriptionTable.timeFixedUpdated} >= ${week.start} THEN ${SubscriptionTable.fixedUsage} + ${cost}
|
||||
ELSE ${cost}
|
||||
END
|
||||
`,
|
||||
timeFixedUpdated: sql`now()`,
|
||||
timeFixedUpdated: sql`
|
||||
CASE
|
||||
WHEN ${SubscriptionTable.timeFixedUpdated} > ${trackedAt} THEN ${SubscriptionTable.timeFixedUpdated}
|
||||
ELSE ${trackedAt}
|
||||
END
|
||||
`,
|
||||
rollingUsage: sql`
|
||||
CASE
|
||||
WHEN UNIX_TIMESTAMP(${SubscriptionTable.timeRollingUpdated}) >= UNIX_TIMESTAMP(now()) - ${rollingWindowSeconds} THEN ${SubscriptionTable.rollingUsage} + ${cost}
|
||||
@@ -1185,8 +1193,8 @@ export async function handler(
|
||||
}
|
||||
if (billingSource === "lite") {
|
||||
const lite = LiteData.getLimits()
|
||||
const week = getWeekBounds(new Date())
|
||||
const month = getMonthlyBounds(new Date(), authInfo.lite!.timeCreated)
|
||||
const week = getWeekBounds(trackedAt)
|
||||
const month = getMonthlyBounds(trackedAt, authInfo.lite!.timeCreated)
|
||||
const rollingWindowSeconds = lite.rollingWindow * 3600
|
||||
const quotaCost = Math.round(cost * modelInfo.costMultiplier)
|
||||
return [
|
||||
@@ -1195,18 +1203,30 @@ export async function handler(
|
||||
.set({
|
||||
monthlyUsage: sql`
|
||||
CASE
|
||||
WHEN ${LiteTable.timeMonthlyUpdated} >= ${month.end} THEN ${LiteTable.monthlyUsage}
|
||||
WHEN ${LiteTable.timeMonthlyUpdated} >= ${month.start} THEN ${LiteTable.monthlyUsage} + ${quotaCost}
|
||||
ELSE ${quotaCost}
|
||||
END
|
||||
`,
|
||||
timeMonthlyUpdated: sql`now()`,
|
||||
timeMonthlyUpdated: sql`
|
||||
CASE
|
||||
WHEN ${LiteTable.timeMonthlyUpdated} > ${trackedAt} THEN ${LiteTable.timeMonthlyUpdated}
|
||||
ELSE ${trackedAt}
|
||||
END
|
||||
`,
|
||||
weeklyUsage: sql`
|
||||
CASE
|
||||
WHEN ${LiteTable.timeWeeklyUpdated} >= ${week.end} THEN ${LiteTable.weeklyUsage}
|
||||
WHEN ${LiteTable.timeWeeklyUpdated} >= ${week.start} THEN ${LiteTable.weeklyUsage} + ${quotaCost}
|
||||
ELSE ${quotaCost}
|
||||
END
|
||||
`,
|
||||
timeWeeklyUpdated: sql`now()`,
|
||||
timeWeeklyUpdated: sql`
|
||||
CASE
|
||||
WHEN ${LiteTable.timeWeeklyUpdated} > ${trackedAt} THEN ${LiteTable.timeWeeklyUpdated}
|
||||
ELSE ${trackedAt}
|
||||
END
|
||||
`,
|
||||
rollingUsage: sql`
|
||||
CASE
|
||||
WHEN UNIX_TIMESTAMP(${LiteTable.timeRollingUpdated}) >= UNIX_TIMESTAMP(now()) - ${rollingWindowSeconds} THEN ${LiteTable.rollingUsage} + ${quotaCost}
|
||||
|
||||
@@ -416,8 +416,9 @@ function callOptions(
|
||||
modelID: ID,
|
||||
optionKey: string,
|
||||
): LanguageModelV3CallOptions {
|
||||
const flattened = ProviderShared.flattenToolRequest(request)
|
||||
return {
|
||||
prompt: prompt(request),
|
||||
prompt: prompt(flattened.request),
|
||||
maxOutputTokens: request.generation?.maxTokens,
|
||||
temperature: request.generation?.temperature,
|
||||
stopSequences: request.generation?.stop === undefined ? undefined : [...request.generation.stop],
|
||||
@@ -426,7 +427,7 @@ function callOptions(
|
||||
presencePenalty: request.generation?.presencePenalty,
|
||||
frequencyPenalty: request.generation?.frequencyPenalty,
|
||||
seed: request.generation?.seed,
|
||||
tools: request.tools.map(tool),
|
||||
tools: flattened.tools.map(tool),
|
||||
toolChoice: toolChoice(request.toolChoice),
|
||||
headers: request.http?.headers,
|
||||
providerOptions: requestProviderOptions(request.providerOptions, packageName, modelID, optionKey),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/effect/integration"
|
||||
import type { SessionRequestKind } from "@opencode-ai/plugin/effect/session"
|
||||
import { Effect, Option, Schema, Semaphore, Stream } from "effect"
|
||||
import { Catalog } from "../../catalog.js"
|
||||
import { Credential } from "../../credential.js"
|
||||
import { Bus } from "../../bus.js"
|
||||
import { CopilotModels } from "../../github-copilot/models.js"
|
||||
import { App } from "../../app.js"
|
||||
import { Agent } from "../../agent.js"
|
||||
import { Integration } from "../../integration.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
@@ -250,15 +250,26 @@ export const GithubCopilotPlugin = define({
|
||||
evt.sdk = mod.createOpenaiCompatible(evt.options)
|
||||
}),
|
||||
)
|
||||
// Runs for every route, unlike http.request, which the AI SDK route bypasses.
|
||||
yield* ctx.session.hook(
|
||||
"model.request",
|
||||
(evt) =>
|
||||
Effect.gen(function* () {
|
||||
if (evt.model.providerID !== Provider.ID.githubCopilot) return
|
||||
const session = yield* ctx.session
|
||||
.get({ sessionID: evt.sessionID })
|
||||
.pipe(Effect.orElseSucceed(() => undefined))
|
||||
const interaction = interactionType(evt.kind, session?.parentID !== undefined)
|
||||
evt.headers["X-Interaction-Type"] = interaction
|
||||
if (interaction !== "conversation-agent") evt.headers["x-initiator"] = "agent"
|
||||
}),
|
||||
{ providerID: Provider.ID.githubCopilot },
|
||||
)
|
||||
yield* ctx.session.hook(
|
||||
"http.request",
|
||||
(evt) =>
|
||||
Effect.gen(function* () {
|
||||
if (evt.model.providerID !== Provider.ID.githubCopilot) return
|
||||
if (evt.agent === Agent.ID.make("title"))
|
||||
evt.request.headers.set("X-Interaction-Type", "conversation-background")
|
||||
if (evt.agent === Agent.ID.make("compaction"))
|
||||
evt.request.headers.set("X-Interaction-Type", "conversation-compaction")
|
||||
const token = evt.request.headers.get("x-api-key")
|
||||
if (!token) return
|
||||
const text = yield* Effect.promise(() => evt.request.clone().text())
|
||||
@@ -370,11 +381,23 @@ function applyHeaders(
|
||||
headers.set("User-Agent", App.useragent(app))
|
||||
headers.set("Openai-Intent", "conversation-edits")
|
||||
headers.set("X-GitHub-Api-Version", apiVersion)
|
||||
headers.set("x-initiator", metadata.agent ? "agent" : "user")
|
||||
// The step may already have declared itself agent-initiated (subagent, title, compaction);
|
||||
// the body can only ever escalate to "agent", never back to "user".
|
||||
if (metadata.agent) headers.set("x-initiator", "agent")
|
||||
else if (!headers.has("x-initiator")) headers.set("x-initiator", "user")
|
||||
if (metadata.vision) headers.set("Copilot-Vision-Request", "true")
|
||||
if (anthropic) headers.set("anthropic-beta", "interleaved-thinking-2025-05-14")
|
||||
}
|
||||
|
||||
// Mirrors the Copilot client's X-Interaction-Type vocabulary: the agent loop is the default,
|
||||
// nested sessions are subagents, and title/compaction are the two utility overrides.
|
||||
export function interactionType(kind: SessionRequestKind, child: boolean) {
|
||||
if (kind === "title") return "conversation-background"
|
||||
if (kind === "compaction") return "conversation-compaction"
|
||||
if (child) return "conversation-subagent"
|
||||
return "conversation-agent"
|
||||
}
|
||||
|
||||
type RequestMetadata = ReturnType<typeof requestMetadata>
|
||||
|
||||
function requestMetadata(url: string, body: unknown) {
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
export * as SessionCompaction from "./compaction.js"
|
||||
|
||||
import { LLMClient, LLMEvent, LLMRequest, Message, type ContentPart } from "@opencode-ai/ai"
|
||||
import {
|
||||
AIError,
|
||||
InvalidProviderOutputError,
|
||||
UnknownProviderError,
|
||||
isContextOverflowFailure,
|
||||
LLMClient,
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
Message,
|
||||
type ContentPart,
|
||||
} from "@opencode-ai/ai"
|
||||
import { Agent } from "@opencode-ai/schema/agent"
|
||||
import { SessionError } from "@opencode-ai/schema/session-error"
|
||||
import { Context, Effect, Layer, Stream } from "effect"
|
||||
@@ -12,6 +22,7 @@ import type { SessionContext } from "./context.js"
|
||||
import type { SessionMessage } from "./message.js"
|
||||
import { SessionModelRequest } from "./model-request.js"
|
||||
import type { SessionRunnerModel } from "./runner/model.js"
|
||||
import { SessionRunnerRetry } from "./runner/retry.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { toSessionError } from "./to-session-error.js"
|
||||
import { Token } from "../util/token.js"
|
||||
@@ -40,7 +51,7 @@ const SUMMARY_TEMPLATE = `You MUST use this format for your response (you may om
|
||||
|
||||
## Work State
|
||||
### Completed
|
||||
- [finished work, verified facts, or changes made; otherwise "(none)"]
|
||||
- [finished work or changes made; otherwise "(none)"]
|
||||
|
||||
### Active
|
||||
- [current work, partial changes, or investigation state; otherwise "(none)"]
|
||||
@@ -385,6 +396,7 @@ export const layer = Layer.effect(
|
||||
messages: history.messages,
|
||||
})
|
||||
const prepared = yield* input.prepare({
|
||||
kind: "compaction",
|
||||
scope: {
|
||||
session: context.session,
|
||||
agentID: Agent.ID.make("compaction"),
|
||||
@@ -405,68 +417,105 @@ export const layer = Layer.effect(
|
||||
],
|
||||
},
|
||||
})
|
||||
// Ignored tool calls never enter the follow-up history or need fabricated results.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
chunks.length = 0
|
||||
providerState = undefined
|
||||
yield* llm
|
||||
.stream(
|
||||
attempt === 0
|
||||
? prepared.request
|
||||
: LLMRequest.update(prepared.request, {
|
||||
messages: [
|
||||
...prepared.request.messages,
|
||||
Message.user(
|
||||
"The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template.",
|
||||
),
|
||||
],
|
||||
}),
|
||||
prepared.options,
|
||||
)
|
||||
.pipe(
|
||||
Stream.runForEach((event) => {
|
||||
if (LLMEvent.is.providerError(event))
|
||||
failure = {
|
||||
type: event.classification === "context-overflow" ? "provider.invalid-request" : "provider.error",
|
||||
message: event.message,
|
||||
}
|
||||
if (LLMEvent.is.textDelta(event)) {
|
||||
chunks.push(event.text)
|
||||
return bus.publish(SessionEvent.Compaction.Delta, {
|
||||
sessionID: context.session.id,
|
||||
text: event.text,
|
||||
})
|
||||
}
|
||||
if (LLMEvent.is.stepFinish(event)) {
|
||||
providerState =
|
||||
event.providerMetadata?.[
|
||||
context.model.model.route.providerMetadataKey ?? context.model.model.provider
|
||||
]
|
||||
const step = SessionUsage.record(event.usage, context.model.cost)
|
||||
usage = usage ? SessionUsage.add(usage, step) : step
|
||||
}
|
||||
return Effect.void
|
||||
}),
|
||||
Effect.catchTag("AI.Error", (error) =>
|
||||
Effect.sync(() => {
|
||||
failure = toSessionError(error)
|
||||
}),
|
||||
const retry = yield* SessionRunnerRetry.policy(context.session.id)
|
||||
// Both requests share the retry allowance; rejected output never enters the reminder request.
|
||||
for (const request of [
|
||||
prepared.request,
|
||||
LLMRequest.update(prepared.request, {
|
||||
messages: [
|
||||
...prepared.request.messages,
|
||||
Message.user(
|
||||
"The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template.",
|
||||
),
|
||||
Effect.onInterrupt(() =>
|
||||
recordUsage.pipe(
|
||||
Effect.andThen(
|
||||
input.reason === "auto"
|
||||
? failed({
|
||||
sessionID: context.session.id,
|
||||
reason: input.reason,
|
||||
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
|
||||
inputID: input.inputID,
|
||||
}).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
],
|
||||
}),
|
||||
]) {
|
||||
yield* Stream.suspend(() => {
|
||||
chunks.length = 0
|
||||
providerState = undefined
|
||||
failure = undefined
|
||||
return llm.stream(request, prepared.options)
|
||||
}).pipe(
|
||||
Stream.runForEach((event) => {
|
||||
if (LLMEvent.is.providerError(event))
|
||||
failure = {
|
||||
type: event.classification === "context-overflow" ? "provider.invalid-request" : "provider.error",
|
||||
message: event.message,
|
||||
}
|
||||
if (LLMEvent.is.textDelta(event)) {
|
||||
chunks.push(event.text)
|
||||
return bus.publish(SessionEvent.Compaction.Delta, {
|
||||
sessionID: context.session.id,
|
||||
text: event.text,
|
||||
})
|
||||
}
|
||||
if (LLMEvent.is.stepFinish(event)) {
|
||||
providerState =
|
||||
event.providerMetadata?.[context.model.model.route.providerMetadataKey ?? context.model.model.provider]
|
||||
const step = SessionUsage.record(event.usage, context.model.cost)
|
||||
usage = usage ? SessionUsage.add(usage, step) : step
|
||||
}
|
||||
if (LLMEvent.is.finish(event)) {
|
||||
if (event.reason.normalized === "length")
|
||||
failure = { type: "compaction.failed", message: "Compaction summary reached the output token limit" }
|
||||
if (event.reason.normalized === "content-filter")
|
||||
failure = {
|
||||
type: "provider.content-filter",
|
||||
message: "Compaction summary was blocked by the provider",
|
||||
}
|
||||
if (event.reason.normalized === "unknown")
|
||||
return Effect.fail(
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
message: "The provider response ended with an unknown finish reason.",
|
||||
classification: "incomplete-stream",
|
||||
}),
|
||||
}),
|
||||
)
|
||||
if (event.reason.normalized === "error")
|
||||
return Effect.fail(
|
||||
new AIError({ reason: new UnknownProviderError({ message: "Compaction generation failed" }) }),
|
||||
)
|
||||
}
|
||||
return Effect.void
|
||||
}),
|
||||
Effect.retry({
|
||||
while: (cause) =>
|
||||
Effect.gen(function* () {
|
||||
if (isContextOverflowFailure(cause)) return false
|
||||
const decision = yield* retry({
|
||||
cause,
|
||||
error: toSessionError(cause),
|
||||
agent: Agent.ID.make("compaction"),
|
||||
model: context.model.ref,
|
||||
hook: prepared.retry,
|
||||
retry: SessionRunnerRetry.isRetryable(cause),
|
||||
})
|
||||
if (!decision.retry) return false
|
||||
yield* Effect.sleep(decision.delay)
|
||||
return true
|
||||
}),
|
||||
}),
|
||||
Effect.catchTag("AI.Error", (error) =>
|
||||
Effect.sync(() => {
|
||||
failure = toSessionError(error)
|
||||
}),
|
||||
),
|
||||
Effect.onInterrupt(() =>
|
||||
recordUsage.pipe(
|
||||
Effect.andThen(
|
||||
input.reason === "auto"
|
||||
? failed({
|
||||
sessionID: context.session.id,
|
||||
reason: input.reason,
|
||||
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
|
||||
inputID: input.inputID,
|
||||
}).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
if (failure || hasSummarySection(chunks.join(""))) break
|
||||
}
|
||||
yield* recordUsage
|
||||
|
||||
@@ -38,6 +38,7 @@ export const generate = Effect.fn("SessionGenerate.generate")(function* (input:
|
||||
messages: history.messages,
|
||||
})
|
||||
const prepared = yield* context.prepare({
|
||||
kind: "generate",
|
||||
scope: { session: selection.session, agentID: selection.agent.id, model, tools: selection.tools },
|
||||
transcript: {
|
||||
system: transcript.system,
|
||||
|
||||
@@ -2,6 +2,7 @@ export * as SessionModelRequest from "./model-request.js"
|
||||
|
||||
import { HttpOptions, LanguageModel, LLM, LLMRequest, Message, SystemPart } from "@opencode-ai/ai"
|
||||
import type { StreamOptions } from "@opencode-ai/ai/route"
|
||||
import type { SessionRequestKind } from "@opencode-ai/plugin/effect/session"
|
||||
import type { Agent } from "@opencode-ai/schema/agent"
|
||||
import type { Model } from "@opencode-ai/schema/model"
|
||||
import type { Content } from "@opencode-ai/schema/tool"
|
||||
@@ -59,6 +60,8 @@ export interface Prepared {
|
||||
}
|
||||
|
||||
interface PrepareInput {
|
||||
/** Which Session flow issues this request; request hooks receive it alongside the Session identity. */
|
||||
readonly kind: SessionRequestKind
|
||||
readonly scope: {
|
||||
readonly session: SessionSchema.Info
|
||||
readonly agentID: Agent.ID
|
||||
@@ -197,6 +200,7 @@ interface HookScope {
|
||||
readonly sessionID: SessionSchema.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
}
|
||||
|
||||
const sessionHeaders = (session: Pick<SessionSchema.Info, "id" | "parentID" | "projectID">, app: App.Info) => ({
|
||||
@@ -325,7 +329,7 @@ export const layer = Layer.effect(
|
||||
)
|
||||
const request = yield* applyModelHooks(
|
||||
hooks,
|
||||
{ sessionID: session.id, agent: input.scope.agentID, model: resolved.ref },
|
||||
{ sessionID: session.id, agent: input.scope.agentID, model: resolved.ref, kind: input.kind },
|
||||
LLM.request({
|
||||
model,
|
||||
http: {
|
||||
@@ -356,6 +360,7 @@ export const layer = Layer.effect(
|
||||
sessionID: session.id,
|
||||
agent: input.scope.agentID,
|
||||
model: resolved.ref,
|
||||
kind: input.kind,
|
||||
})
|
||||
: undefined
|
||||
const options: StreamOptions = {
|
||||
|
||||
@@ -217,6 +217,7 @@ const layer = Layer.effect(
|
||||
messages: loaded.messages,
|
||||
})
|
||||
const prepared = yield* context.prepare({
|
||||
kind: "primary",
|
||||
scope: { session: loaded.session, agentID: loaded.agent.id, model: loaded.model, tools: loaded.tools },
|
||||
transcript: {
|
||||
system: transcript.system,
|
||||
|
||||
@@ -78,11 +78,11 @@ const schedule = Schedule.max([Schedule.exponential("2 seconds"), Schedule.recur
|
||||
}),
|
||||
)
|
||||
|
||||
export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
export const policy = (sessionID: SessionSchema.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const step = yield* Schedule.toStep(schedule)
|
||||
let attempt = 1
|
||||
const decide = (input: Input) =>
|
||||
return (input: Input) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const next = yield* step(now, input).pipe(Pull.catchDone(() => Effect.succeed(undefined)))
|
||||
@@ -104,6 +104,11 @@ export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
Number.isFinite(event.decision.delay) && event.decision.delay >= 0 ? Math.ceil(event.decision.delay) : delay
|
||||
return { retry: true as const, attempt, delay: normalized }
|
||||
})
|
||||
})
|
||||
|
||||
export const make = (bus: Bus.Interface, sessionID: SessionSchema.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const decide = yield* policy(sessionID)
|
||||
const wait = (input: {
|
||||
readonly decision: Decision
|
||||
readonly assistantMessageID: SessionMessage.ID
|
||||
|
||||
@@ -64,6 +64,7 @@ export const layer = Layer.effect(
|
||||
: Effect.void,
|
||||
)
|
||||
const prepared = yield* context.prepare({
|
||||
kind: "title",
|
||||
scope: { session: input.session, agentID: input.agent.id, model: input.model },
|
||||
transcript: {
|
||||
system: input.agent.system ? [SystemPart.make(input.agent.system)] : [],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * as OpenCodeTools from "./opencode.js"
|
||||
|
||||
import { ToolFailure } from "@opencode-ai/ai"
|
||||
import { SystemPart, ToolFailure } from "@opencode-ai/ai"
|
||||
import type { Context } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { AbsolutePath } from "@opencode-ai/schema/schema"
|
||||
import { Session } from "@opencode-ai/schema/session"
|
||||
@@ -18,6 +18,15 @@ const MoveOutput = Schema.Struct({ sessionID: Session.ID, directory: AbsolutePat
|
||||
export const Plugin = {
|
||||
id: "opencode.tools",
|
||||
effect: Effect.fn("OpenCodeTools.Plugin")(function* (ctx: Context) {
|
||||
yield* ctx.session.hook("context", (event) =>
|
||||
Effect.sync(() => {
|
||||
event.system.push(
|
||||
SystemPart.make(
|
||||
"When you create a worktree outside the current working directory and intend to use it as your primary working directory, consider using `execute` to call `tools.opencode.session_move` and make the worktree the session's working directory.",
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
yield* ctx.tool
|
||||
.transform((draft) => {
|
||||
draft.namespace({ name: "opencode", description: "OpenCode session and runtime tools." })
|
||||
|
||||
@@ -18,6 +18,7 @@ const jsonSchemas = Effect.runSync(
|
||||
)
|
||||
|
||||
export const definition = (tool: Tool.Info<any, any>): ToolDefinition => ({
|
||||
type: "tool",
|
||||
name: effectiveName(tool),
|
||||
description: tool.description,
|
||||
inputSchema: inputJsonSchema(tool.input),
|
||||
|
||||
@@ -281,6 +281,7 @@ describe("AzurePlugin", () => {
|
||||
sessionID: Session.ID.make("ses_azure"),
|
||||
agent: Agent.ID.make("build"),
|
||||
model,
|
||||
kind: "primary",
|
||||
request: new Request("https://test-resource.openai.azure.com/openai/v1/responses", {
|
||||
headers: { "api-key": "stored-token", "x-keep": "yes" },
|
||||
}),
|
||||
@@ -295,6 +296,7 @@ describe("AzurePlugin", () => {
|
||||
sessionID: Session.ID.make("ses_foundry"),
|
||||
agent: Agent.ID.make("build"),
|
||||
model,
|
||||
kind: "primary",
|
||||
request: new Request("https://test-resource.services.ai.azure.com/anthropic/v1/messages", {
|
||||
headers: { "x-api-key": "stored-token" },
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { AISDK } from "@opencode-ai/core/aisdk"
|
||||
import { App } from "@opencode-ai/core/app"
|
||||
import { Agent } from "@opencode-ai/schema/agent"
|
||||
import { Session } from "@opencode-ai/schema/session"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
} from "@opencode-ai/core/plugin/provider/github-copilot"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { Integration } from "@opencode-ai/core/integration"
|
||||
import type { SessionRequestKind } from "@opencode-ai/plugin/effect/session"
|
||||
import { fakeSelectorSdk } from "../fixture/selector"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
@@ -35,6 +37,25 @@ function required<T>(value: T | undefined): T {
|
||||
return value
|
||||
}
|
||||
|
||||
const sessions = Effect.fn(function* () {
|
||||
const service = yield* Session.Service
|
||||
const location = yield* Location.Service
|
||||
const parent = yield* service.create({ location: { directory: location.directory } })
|
||||
const child = yield* service.create({ parentID: parent.id })
|
||||
return { parent: parent.id, child: child.id }
|
||||
})
|
||||
|
||||
const modelRequest = Effect.fn(function* (sessionID: Session.ID, kind: SessionRequestKind, agent = "build") {
|
||||
const hooks = yield* PluginHooks.Service
|
||||
return yield* hooks.trigger("session", "model.request", {
|
||||
sessionID,
|
||||
agent: Agent.ID.make(agent),
|
||||
model: Model.Ref.make({ providerID: Provider.ID.githubCopilot, id: Model.ID.make("gpt-5.4") }),
|
||||
kind,
|
||||
headers: {},
|
||||
})
|
||||
})
|
||||
|
||||
describe("GithubCopilotPlugin", () => {
|
||||
test("prefers the account-specific Copilot API endpoint", () => {
|
||||
expect(
|
||||
@@ -135,6 +156,7 @@ describe("GithubCopilotPlugin", () => {
|
||||
sessionID: Session.ID.make("ses_test"),
|
||||
agent: Agent.ID.make("build"),
|
||||
model: Model.Ref.make({ providerID: Provider.ID.githubCopilot, id: Model.ID.make("claude-sonnet-4.5") }),
|
||||
kind: "primary",
|
||||
request: new Request("https://api.githubcopilot.com/v1/messages", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "x-api-key": "token" },
|
||||
@@ -149,31 +171,88 @@ describe("GithubCopilotPlugin", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies title generation as a background interaction", () =>
|
||||
it.effect("classifies main-loop steps as agent interactions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const event = yield* hooks.trigger("session", "http.request", {
|
||||
sessionID: Session.ID.make("ses_title"),
|
||||
agent: Agent.ID.make("title"),
|
||||
model: Model.Ref.make({ providerID: Provider.ID.githubCopilot, id: Model.ID.make("gpt-5.4-nano") }),
|
||||
request: new Request("https://api.githubcopilot.com/chat/completions"),
|
||||
})
|
||||
expect(event.request.headers.get("x-interaction-type")).toBe("conversation-background")
|
||||
const event = yield* modelRequest((yield* sessions()).parent, "primary")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies compaction requests", () =>
|
||||
it.effect("classifies child-session steps as subagent interactions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const event = yield* modelRequest((yield* sessions()).child, "primary")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-subagent", "x-initiator": "agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies title generation as a background interaction", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const event = yield* modelRequest((yield* sessions()).parent, "title")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-background", "x-initiator": "agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies compaction requests by kind rather than agent", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const event = yield* modelRequest((yield* sessions()).child, "compaction", "build")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-compaction", "x-initiator": "agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("does not classify by agent name", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const event = yield* modelRequest((yield* sessions()).parent, "primary", "compaction")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("ignores other providers' model requests", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const event = yield* hooks.trigger("session", "http.request", {
|
||||
sessionID: Session.ID.make("ses_compaction"),
|
||||
agent: Agent.ID.make("compaction"),
|
||||
model: Model.Ref.make({ providerID: Provider.ID.githubCopilot, id: Model.ID.make("gpt-5.4") }),
|
||||
request: new Request("https://api.githubcopilot.com/responses"),
|
||||
const event = yield* hooks.trigger("session", "model.request", {
|
||||
sessionID: (yield* sessions()).parent,
|
||||
agent: Agent.ID.make("build"),
|
||||
model: Model.Ref.make({ providerID: Provider.ID.make("openai"), id: Model.ID.make("gpt-5.4") }),
|
||||
kind: "primary",
|
||||
headers: {},
|
||||
})
|
||||
expect(event.request.headers.get("x-interaction-type")).toBe("conversation-compaction")
|
||||
expect(event.headers).toEqual({})
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("keeps a declared agent initiator when the body looks user-initiated", () =>
|
||||
Effect.gen(function* () {
|
||||
const requests: Headers[] = []
|
||||
const send = copilotFetch(
|
||||
"token",
|
||||
async (_input: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||||
requests.push(new Headers(init?.headers))
|
||||
return Response.json({ ok: true })
|
||||
},
|
||||
App.make({ name: "test", version: "1.2.3", channel: "beta" }),
|
||||
)
|
||||
yield* Effect.promise(() =>
|
||||
send("https://api.githubcopilot.com/chat/completions", {
|
||||
method: "POST",
|
||||
headers: { "x-initiator": "agent" },
|
||||
body: JSON.stringify({ messages: [{ role: "user", content: "summarize" }] }),
|
||||
}),
|
||||
)
|
||||
expect(requests[0]?.get("x-initiator")).toBe("agent")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("classifies session generation requests as agent interactions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
const event = yield* modelRequest((yield* sessions()).parent, "generate")
|
||||
expect(event.headers).toEqual({ "X-Interaction-Type": "conversation-agent" })
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ const request = Effect.fn(function* (providerID: Provider.ID, baseURL: string) {
|
||||
sessionID: Session.ID.make("ses_test"),
|
||||
agent: Agent.ID.make("build"),
|
||||
model: Model.Ref.make({ providerID, id: Model.ID.make("gpt-5.5") }),
|
||||
kind: "primary",
|
||||
baseURL,
|
||||
headers: {},
|
||||
})
|
||||
@@ -226,6 +227,7 @@ describe("OpenAIPlugin", () => {
|
||||
const program = Effect.gen(function* () {
|
||||
const requests = yield* SessionModelRequest.Service
|
||||
return yield* requests.prepare({
|
||||
kind: "primary",
|
||||
scope: {
|
||||
session: Session.Info.make({
|
||||
id: sessionID,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { OpenAIChat } from "@opencode-ai/ai/protocols"
|
||||
import { Agent } from "@opencode-ai/schema/agent"
|
||||
import { Money } from "@opencode-ai/schema/money"
|
||||
import { Session } from "@opencode-ai/schema/session"
|
||||
import type { SessionRequestKind } from "@opencode-ai/plugin/effect/session"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
|
||||
import { Project } from "@opencode-ai/core/project"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { SessionModelRequest } from "@opencode-ai/core/session/model-request"
|
||||
import { SessionModelTransport } from "@opencode-ai/core/session/model-transport"
|
||||
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
|
||||
import { DateTime, Effect } from "effect"
|
||||
import { HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { PluginTestLayer } from "./plugin/fixture"
|
||||
|
||||
const it = testEffect(PluginTestLayer)
|
||||
|
||||
const KINDS: ReadonlyArray<SessionRequestKind> = ["primary", "compaction", "title", "generate"]
|
||||
|
||||
const session = Session.Info.make({
|
||||
id: Session.ID.make("ses_hook_kind"),
|
||||
projectID: Project.ID.global,
|
||||
cost: Money.USD.zero,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make("/project") }),
|
||||
})
|
||||
const model = SessionRunnerModel.resolved(OpenAIChat.route.model({ id: "gpt-5.5", provider: "test" }), {
|
||||
capabilities: { tools: true, input: ["text"], output: ["text"] },
|
||||
cost: [],
|
||||
limit: { context: 200_000, output: 32_000 },
|
||||
})
|
||||
const transport = SessionModelTransport.Service.of({
|
||||
bind: () => ({ execute: () => Effect.die("unused WebSocket execution") }),
|
||||
close: () => Effect.void,
|
||||
closeAll: Effect.void,
|
||||
})
|
||||
|
||||
describe("SessionModelRequest HTTP hooks", () => {
|
||||
it.effect("tags every Session request kind on http.request and http.response", () =>
|
||||
Effect.gen(function* () {
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const seen: Array<{ hook: string; kind: SessionRequestKind; agent: Agent.ID }> = []
|
||||
yield* hooks.register("session", "http.request", (event) =>
|
||||
Effect.sync(() => {
|
||||
seen.push({ hook: "request", kind: event.kind, agent: event.agent })
|
||||
}),
|
||||
)
|
||||
yield* hooks.register("session", "http.response", (event) =>
|
||||
Effect.sync(() => {
|
||||
seen.push({ hook: "response", kind: event.kind, agent: event.agent })
|
||||
}),
|
||||
)
|
||||
const requests = yield* SessionModelRequest.Service.pipe(Effect.provide(SessionModelRequest.layer))
|
||||
|
||||
for (const kind of KINDS) {
|
||||
const prepared = yield* requests.prepare({
|
||||
kind,
|
||||
scope: { session, agentID: Agent.ID.make("build"), model },
|
||||
transcript: { system: [], messages: [] },
|
||||
})
|
||||
const http = prepared.options.http
|
||||
if (!http) throw new Error(`Expected HTTP middleware for ${kind}`)
|
||||
yield* http(HttpClientRequest.post("https://example.test/v1/chat/completions"), (request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, new Response("{}", { status: 200 }))),
|
||||
)
|
||||
}
|
||||
|
||||
expect(seen).toEqual(
|
||||
KINDS.flatMap((kind) => [
|
||||
{ hook: "request", kind, agent: Agent.ID.make("build") },
|
||||
{ hook: "response", kind, agent: Agent.ID.make("build") },
|
||||
]),
|
||||
)
|
||||
}).pipe(Effect.provideService(SessionModelTransport.Service, transport)),
|
||||
)
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
AIError,
|
||||
HttpContext,
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
Message,
|
||||
@@ -2260,21 +2261,151 @@ describe("SessionRunnerLLM", () => {
|
||||
}
|
||||
}
|
||||
|
||||
scenario("preserves typed provider failures from manual compaction", function* (s) {
|
||||
scenario("restarts compaction drafts after transient failures and unsuccessful finishes", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "text-manual-failure-history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
|
||||
yield* s.llm.push(Stream.fail(providerUnavailable()))
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const retries: PluginHooks.Domains["session"]["retry"][] = []
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
retries.push({ ...event })
|
||||
event.decision = { retry: true, delay: 0 }
|
||||
}),
|
||||
)
|
||||
const draft = TestLLM.complete(
|
||||
{
|
||||
reason: { normalized: "unknown" },
|
||||
usage: { nonCachedInputTokens: 10 },
|
||||
providerMetadata: { openai: { responseId: "discarded-draft" } },
|
||||
},
|
||||
LLMEvent.textDelta({ id: "draft", text: "## Objective\n- Partial draft" }),
|
||||
)
|
||||
yield* s.llm.push(
|
||||
TestLLM.failAfter(streamDisconnected(), ...draft.slice(0, -1)),
|
||||
draft,
|
||||
TestLLM.complete(
|
||||
{ reason: { normalized: "error" } },
|
||||
LLMEvent.textDelta({ id: "failed", text: "## Objective\n- Failed draft" }),
|
||||
),
|
||||
Stream.fail(rateLimited(60_000)),
|
||||
TestLLM.textWithUsage("## Objective\n- Accepted summary", "accepted", 30),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(5)
|
||||
for (const request of s.requests) expect(request).toEqual(s.requests[0])
|
||||
expect(retries.map((event) => event.attempt)).toEqual([2, 3, 4, 5])
|
||||
expect(retries.every((event) => event.sessionID === sessionID && event.agent === "compaction")).toBe(true)
|
||||
expect(retries[3].decision).toEqual({ retry: true, delay: 60_000 })
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
status: "completed",
|
||||
summary: "## Objective\n- Accepted summary",
|
||||
})
|
||||
expect(JSON.stringify(yield* s.messages)).not.toContain("discarded-draft")
|
||||
expect((yield* s.session.get(sessionID))?.tokens.input).toBe(50)
|
||||
})
|
||||
|
||||
scenario("bounds compaction network retries across a template correction", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const attempts: number[] = []
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
attempts.push(event.attempt)
|
||||
expect(event.decision).toMatchObject({ retry: true })
|
||||
event.decision = { retry: true, delay: 0 }
|
||||
}),
|
||||
)
|
||||
yield* s.llm.push(Stream.fail(providerUnavailable()), TestLLM.text("Not a summary", "invalid"))
|
||||
yield* s.llm.always(Stream.fail(providerUnavailable()))
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(attempts).toEqual([2, 3, 4, 5])
|
||||
expect(s.requests).toHaveLength(6)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
type: "compaction",
|
||||
status: "failed",
|
||||
error: { type: "provider.transport", message: "Provider unavailable" },
|
||||
})
|
||||
expect((yield* s.context).some((message) => message.type === "user" && message.text === "Earlier question")).toBe(
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
for (const header of [false, true]) {
|
||||
scenario(`stops compaction retries through the ${header ? "provider header" : "retry hook"}`, function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
const hooks = yield* PluginHooks.Service
|
||||
yield* hooks.register("session", "retry", (event) =>
|
||||
Effect.sync(() => {
|
||||
expect(event.decision.retry).toBe(!header)
|
||||
event.decision = { retry: false }
|
||||
}),
|
||||
)
|
||||
yield* s.llm.push(
|
||||
Stream.fail(
|
||||
header
|
||||
? new AIError({
|
||||
reason: new TransportError({
|
||||
message: "Connection closed",
|
||||
transport: "http",
|
||||
operation: "read",
|
||||
http: new HttpContext({
|
||||
url: "https://example.com",
|
||||
status: 200,
|
||||
headers: { "x-should-retry": "false" },
|
||||
}),
|
||||
}),
|
||||
})
|
||||
: incompleteStream(),
|
||||
),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(1)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({
|
||||
status: "failed",
|
||||
error: { type: header ? "provider.transport" : "provider.invalid-output" },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
for (const response of ["length", "content-filter", "context overflow"] as const) {
|
||||
scenario(`rejects compaction ${response} without retrying or committing its draft`, function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
s.requests.length = 0
|
||||
yield* s.llm.push(
|
||||
response === "context overflow"
|
||||
? Stream.fail(
|
||||
new AIError({
|
||||
reason: new InvalidRequestError({ message: "Too long", classification: "context-overflow" }),
|
||||
}),
|
||||
)
|
||||
: TestLLM.complete(
|
||||
{ reason: { normalized: response } },
|
||||
LLMEvent.textDelta({ id: "truncated", text: "## Objective\n- Incomplete summary" }),
|
||||
),
|
||||
)
|
||||
const compaction = yield* s.session.compact({ sessionID })
|
||||
yield* s.resume
|
||||
|
||||
expect(s.requests).toHaveLength(1)
|
||||
expect((yield* s.messages).find((message) => message.id === compaction.id)).toMatchObject({ status: "failed" })
|
||||
yield* s.llm.push(TestLLM.text("Continued", "continued"))
|
||||
yield* s.runPrompt("Continue")
|
||||
expect(userTexts(s.requests[1])).toContain("Earlier question")
|
||||
expect(JSON.stringify(s.requests[1])).not.toContain("Incomplete summary")
|
||||
})
|
||||
}
|
||||
|
||||
scenario("records cancelled manual compaction without surfacing an internal failure", function* (s) {
|
||||
yield* s.llm.push(TestLLM.text("Earlier answer", "text-manual-interrupt-history"))
|
||||
yield* s.runPrompt("Earlier question")
|
||||
|
||||
@@ -27,6 +27,7 @@ test("tools are structural values", async () => {
|
||||
const tool: Info = config
|
||||
|
||||
expect(definition(tool)).toEqual({
|
||||
type: "tool",
|
||||
name: "foreign",
|
||||
description: "Foreign tool",
|
||||
inputSchema: {
|
||||
@@ -142,6 +143,7 @@ test("portable schemas validate and describe typed tools", async () => {
|
||||
}
|
||||
|
||||
expect(definition(tool)).toEqual({
|
||||
type: "tool",
|
||||
name: "portable",
|
||||
description: "Portable tool",
|
||||
inputSchema: { type: "object", properties: { count: { type: "string" } } },
|
||||
@@ -161,6 +163,7 @@ test("Zod schemas validate, transform, and describe typed tools", async () => {
|
||||
}
|
||||
|
||||
expect(definition(tool)).toEqual({
|
||||
type: "tool",
|
||||
name: "zod",
|
||||
description: "Zod tool",
|
||||
inputSchema: {
|
||||
@@ -317,6 +320,7 @@ test("raw JSON schemas validate and decode tool input", async () => {
|
||||
}
|
||||
|
||||
expect(definition(tool)).toEqual({
|
||||
type: "tool",
|
||||
name: "raw",
|
||||
description: "Raw tool",
|
||||
inputSchema: input,
|
||||
@@ -400,6 +404,7 @@ test("missing external input schemas fall back to an empty schema", () => {
|
||||
} as unknown as Info
|
||||
|
||||
expect(definition(tool)).toEqual({
|
||||
type: "tool",
|
||||
name: "external",
|
||||
description: "External tool",
|
||||
inputSchema: {},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { app, BrowserWindow, MessageChannelMain } from "electron"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { RpcServer } from "effect/unstable/rpc"
|
||||
import { DesktopRpcs } from "../shared/ipc-rpc"
|
||||
import { IpcTransportPort } from "../shared/ipc-transport"
|
||||
import { DragCancelEvent, IpcTransportPort } from "../shared/ipc-transport"
|
||||
import { DesktopFiles, openExternalURL } from "./files"
|
||||
import { appHandlers } from "./ipc-handlers/app"
|
||||
import { eventHandlers } from "./ipc-handlers/events"
|
||||
@@ -59,6 +59,10 @@ export const registerIpcHandlers = Effect.gen(function* () {
|
||||
relaunch: lifecycle.relaunch,
|
||||
}
|
||||
const wire = (_event: Electron.Event, win: BrowserWindow) => {
|
||||
win.webContents.on("before-input-event", (_event, input) => {
|
||||
if (input.type !== "keyDown" || input.key !== "Escape") return
|
||||
win.webContents.send(DragCancelEvent)
|
||||
})
|
||||
win.webContents.on("did-finish-load", () => {
|
||||
if (win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
const channel = new MessageChannelMain()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { contextBridge, ipcRenderer, webUtils } from "electron"
|
||||
import { IpcTransportPort } from "../shared/ipc-transport"
|
||||
import { DragCancelEvent, IpcTransportPort } from "../shared/ipc-transport"
|
||||
import { windowIDFromArguments } from "../shared/window-bootstrap"
|
||||
|
||||
ipcRenderer.on(IpcTransportPort, (event) => {
|
||||
@@ -7,6 +7,8 @@ ipcRenderer.on(IpcTransportPort, (event) => {
|
||||
if (port) window.postMessage(IpcTransportPort, "*", [port])
|
||||
})
|
||||
|
||||
ipcRenderer.on(DragCancelEvent, () => window.dispatchEvent(new Event(DragCancelEvent)))
|
||||
|
||||
contextBridge.exposeInMainWorld("electron", {
|
||||
windowID: windowIDFromArguments(process.argv),
|
||||
getPathForFile: (file: File) => webUtils.getPathForFile(file),
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import type { ElectronAPI } from "../api-types"
|
||||
import { setPinchZoomEnabled, webviewZoom } from "../window/zoom"
|
||||
import { windowFullscreen } from "../window/fullscreen"
|
||||
import { DragCancelEvent } from "../../shared/ipc-transport"
|
||||
import { createDesktopFiles } from "./files"
|
||||
import { createDesktopMenuAction } from "./menu"
|
||||
import { createDesktopNotify } from "./notifications"
|
||||
@@ -53,6 +54,10 @@ export function createDesktopPlatform(
|
||||
windowFullscreen,
|
||||
getPinchZoomEnabled: () => api.getPinchZoomEnabled(),
|
||||
setPinchZoomEnabled,
|
||||
onDragCancel: (callback) => {
|
||||
window.addEventListener(DragCancelEvent, callback)
|
||||
return () => window.removeEventListener(DragCancelEvent, callback)
|
||||
},
|
||||
runDesktopMenuAction: createDesktopMenuAction(api),
|
||||
checkAppExists: async (appName) => {
|
||||
return api.checkAppExists(appName)
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export const IpcTransportPort = "desktop-rpc-port"
|
||||
export const DragCancelEvent = "opencode:drag-cancel"
|
||||
|
||||
@@ -30,10 +30,17 @@ export interface SessionContext {
|
||||
providerOptions: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a Session request is being made. Auxiliary requests share the Session's
|
||||
* hook identity but need to be told apart from the agent loop.
|
||||
*/
|
||||
export type SessionRequestKind = "primary" | "compaction" | "title" | "generate"
|
||||
|
||||
export interface SessionModelRequest {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
baseURL?: string
|
||||
headers: Record<string, string>
|
||||
}
|
||||
@@ -42,6 +49,7 @@ export interface SessionHttpRequest {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
request: Request
|
||||
}
|
||||
|
||||
@@ -49,6 +57,7 @@ export interface SessionHttpResponse {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
readonly request: Request
|
||||
response: Response
|
||||
}
|
||||
|
||||
@@ -30,10 +30,17 @@ export interface SessionContext {
|
||||
providerOptions: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a Session request is being made. Auxiliary requests share the Session's
|
||||
* hook identity but need to be told apart from the agent loop.
|
||||
*/
|
||||
export type SessionRequestKind = "primary" | "compaction" | "title" | "generate"
|
||||
|
||||
export interface SessionModelRequest {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
baseURL?: string
|
||||
headers: Record<string, string>
|
||||
}
|
||||
@@ -42,6 +49,7 @@ export interface SessionHttpRequest {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
request: Request
|
||||
}
|
||||
|
||||
@@ -49,6 +57,7 @@ export interface SessionHttpResponse {
|
||||
readonly sessionID: Session.ID
|
||||
readonly agent: Agent.ID
|
||||
readonly model: Model.Ref
|
||||
readonly kind: SessionRequestKind
|
||||
readonly request: Request
|
||||
response: Response
|
||||
}
|
||||
|
||||
@@ -203,6 +203,8 @@ export namespace Frontend {
|
||||
"ui.focus",
|
||||
"ui.click",
|
||||
"ui.click.semantic",
|
||||
"ui.mouse",
|
||||
"ui.recording.pointer",
|
||||
"ui.resize",
|
||||
"ui.matches",
|
||||
"ui.state",
|
||||
@@ -228,12 +230,39 @@ export namespace Frontend {
|
||||
})
|
||||
export interface SemanticClickTarget extends Schema.Schema.Type<typeof SemanticClickTarget> {}
|
||||
|
||||
const MousePosition = {
|
||||
x: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
y: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
modifiers: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
shift: Schema.optionalKey(Schema.Boolean),
|
||||
alt: Schema.optionalKey(Schema.Boolean),
|
||||
ctrl: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
}
|
||||
export const MouseParams = Schema.Union([
|
||||
Schema.Struct({ ...MousePosition, action: Schema.Literal("move") }),
|
||||
Schema.Struct({
|
||||
...MousePosition,
|
||||
action: Schema.Literals(["down", "up"]),
|
||||
button: Schema.optionalKey(Schema.Literals(["left", "middle", "right"])),
|
||||
}),
|
||||
Schema.Struct({
|
||||
...MousePosition,
|
||||
action: Schema.Literal("scroll"),
|
||||
direction: Schema.Literals(["up", "down", "left", "right"]),
|
||||
}),
|
||||
])
|
||||
export type MouseParams = Schema.Schema.Type<typeof MouseParams>
|
||||
|
||||
export const Action = Schema.Union([
|
||||
Schema.Struct({ type: Schema.Literal("ui.type"), text: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.press"), key: Schema.String, modifiers: Schema.optional(KeyModifiers) }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.enter") }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.arrow"), direction: Schema.Literals(["up", "down", "left", "right"]) }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.focus"), target: Schema.Number }),
|
||||
Schema.Struct({ type: Schema.Literal("ui.mouse"), params: MouseParams }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("ui.click"),
|
||||
target: Schema.Number,
|
||||
@@ -375,6 +404,7 @@ export namespace Frontend {
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.arrow"), params: ArrowParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.focus"), params: FocusParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.click"), params: ClickParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.mouse"), params: MouseParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.resize"), params: ResizeParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.matches"), params: MatchesParams }),
|
||||
Schema.Struct({
|
||||
@@ -631,6 +661,7 @@ export const UiRpcs = RpcGroup.make(
|
||||
request("ui.arrow", { payload: Frontend.ArrowParams, success: Frontend.State }),
|
||||
request("ui.focus", { payload: Frontend.FocusParams, success: Frontend.State }),
|
||||
request("ui.click", { payload: Frontend.ClickParams, success: Frontend.State }),
|
||||
request("ui.mouse", { payload: Frontend.MouseParams, success: Frontend.State }),
|
||||
request("ui.resize", { payload: Frontend.ResizeParams, success: Frontend.State }),
|
||||
)
|
||||
|
||||
|
||||
@@ -528,12 +528,12 @@ export function CurrentContextToolGroup(props: {
|
||||
.join(", "),
|
||||
)
|
||||
const label = createMemo(() => {
|
||||
const notices = props.parts.filter((part) => part.type === "notice").length
|
||||
const title =
|
||||
[names(), notices ? i18n.plural("ui.messagePart.context.notice", notices) : undefined]
|
||||
.filter(Boolean)
|
||||
.join(", ") ||
|
||||
i18n.plural("ui.messagePart.context.thought", props.parts.filter((part) => part.type === "reasoning").length)
|
||||
const thoughts = props.parts.filter((part) => part.type === "reasoning").length
|
||||
if (!names() && !thoughts) {
|
||||
const title = i18n.t("ui.messagePart.context.details")
|
||||
return { text: title, title, before: "", after: "" }
|
||||
}
|
||||
const title = names() || i18n.plural("ui.messagePart.context.thought", thoughts)
|
||||
const text = i18n.t("ui.messagePart.tools.used", { tools: title })
|
||||
const index = text.indexOf(title)
|
||||
return { text, title, before: text.slice(0, index).trim(), after: text.slice(index + title.length).trim() }
|
||||
|
||||
@@ -184,6 +184,32 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
.find((item) => item.num === action.target)
|
||||
?.focus()
|
||||
break
|
||||
case "ui.mouse": {
|
||||
const params = action.params
|
||||
if (params.x >= harness.renderer.width || params.y >= harness.renderer.height)
|
||||
return yield* Effect.fail(new Error("mouse position must be within the terminal viewport"))
|
||||
const options = { modifiers: params.modifiers }
|
||||
SimulationRenderer.recordPointer(harness.renderer, params.action, params.x, params.y)
|
||||
switch (params.action) {
|
||||
case "move":
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.moveTo(params.x, params.y, options))
|
||||
break
|
||||
case "down":
|
||||
yield* Effect.tryPromise(() =>
|
||||
harness.mockMouse.pressDown(params.x, params.y, mouseButton(params.button), options),
|
||||
)
|
||||
break
|
||||
case "up":
|
||||
yield* Effect.tryPromise(() =>
|
||||
harness.mockMouse.release(params.x, params.y, mouseButton(params.button), options),
|
||||
)
|
||||
break
|
||||
case "scroll":
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.scroll(params.x, params.y, params.direction, options))
|
||||
break
|
||||
}
|
||||
break
|
||||
}
|
||||
case "ui.click": {
|
||||
const target = all(harness.renderer.root).find((item) => item.num === action.target)
|
||||
if (!target || !target.visible || target.isDestroyed)
|
||||
@@ -206,6 +232,7 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
action.y >= target.height
|
||||
)
|
||||
return yield* Effect.fail(new Error("click position must be within the target element"))
|
||||
SimulationRenderer.recordPointer(harness.renderer, "click", target.screenX + action.x, target.screenY + action.y)
|
||||
yield* Effect.tryPromise(() => harness.mockMouse.click(target.screenX + action.x, target.screenY + action.y))
|
||||
break
|
||||
}
|
||||
@@ -227,3 +254,7 @@ export const execute = Effect.fn("SimulationActions.execute")(function* (harness
|
||||
})
|
||||
|
||||
export * as SimulationActions from "./actions"
|
||||
|
||||
function mouseButton(button: "left" | "middle" | "right" = "left") {
|
||||
return ({ left: 0, middle: 1, right: 2 } as const)[button]
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CliRenderer, CliRendererConfig } from "@opentui/core"
|
||||
import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
|
||||
import { Effect } from "effect"
|
||||
import { Timeline } from "../recording"
|
||||
import { Timeline, type Pointer } from "../recording"
|
||||
|
||||
const setups = new WeakMap<CliRenderer, TestRendererSetup>()
|
||||
const recordings = new WeakMap<CliRenderer, Timeline>()
|
||||
@@ -64,6 +64,10 @@ export function recordResize(renderer: CliRenderer, cols: number, rows: number)
|
||||
recordings.get(renderer)?.resize(cols, rows)
|
||||
}
|
||||
|
||||
export function recordPointer(renderer: CliRenderer, action: Pointer["action"], x: number, y: number) {
|
||||
recordings.get(renderer)?.pointer(action, x, y)
|
||||
}
|
||||
|
||||
export function setupFor(renderer: CliRenderer): TestRendererSetup | undefined {
|
||||
return setups.get(renderer)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ function handle(harness: Harness, request: SimulationProtocol.Frontend.Request,
|
||||
y: request.params.y,
|
||||
semantic: request.params.semantic,
|
||||
})
|
||||
case "ui.mouse":
|
||||
return SimulationActions.execute(harness, { type: "ui.mouse", params: request.params })
|
||||
case "ui.resize":
|
||||
return SimulationActions.execute(harness, {
|
||||
type: "ui.resize",
|
||||
|
||||
@@ -32,6 +32,14 @@ export interface Resize extends Schema.Schema.Type<typeof Resize> {}
|
||||
export const Event = Schema.Union([Header, Output, Resize])
|
||||
export type Event = Schema.Schema.Type<typeof Event>
|
||||
|
||||
export const Pointer = Schema.Struct({
|
||||
atMs: Schema.Number,
|
||||
action: Schema.Literals(["move", "down", "up", "click", "scroll"]),
|
||||
x: Schema.Number,
|
||||
y: Schema.Number,
|
||||
})
|
||||
export interface Pointer extends Schema.Schema.Type<typeof Pointer> {}
|
||||
|
||||
export class Timeline extends Writable {
|
||||
readonly isTTY = true
|
||||
readonly path: string
|
||||
@@ -41,6 +49,7 @@ export class Timeline extends Writable {
|
||||
private readonly started = performance.now()
|
||||
private readonly timestamps: number[] = []
|
||||
private done?: Promise<string>
|
||||
private pointers?: WriteStream
|
||||
|
||||
private constructor(path: string, cols: number, rows: number, output: WriteStream) {
|
||||
super()
|
||||
@@ -95,14 +104,27 @@ export class Timeline extends Writable {
|
||||
override _final(callback: (error?: Error | null) => void) {
|
||||
this.writeOutput(Buffer.alloc(0), this.elapsed(), (error) => {
|
||||
if (error) return callback(error)
|
||||
this.output.end(callback)
|
||||
this.output.end()
|
||||
this.pointers?.end()
|
||||
void Promise.all(this.streams().map((stream) => finished(stream, { cleanup: true }))).then(
|
||||
() => callback(),
|
||||
callback,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
override _destroy(error: Error | null, callback: (error: Error | null) => void) {
|
||||
const streams = this.streams()
|
||||
const closed = streams.map((stream) => finished(stream, { cleanup: true }))
|
||||
streams.forEach((stream) => stream.destroy())
|
||||
// Destroy joins both children even when one failed before finish() began.
|
||||
void Promise.allSettled(closed).then(() => callback(error))
|
||||
}
|
||||
|
||||
finish() {
|
||||
if (this.done) return this.done
|
||||
this.end()
|
||||
this.done = finished(this).then(() => this.path)
|
||||
this.done = finished(this, { cleanup: true }).then(() => this.path)
|
||||
return this.done
|
||||
}
|
||||
|
||||
@@ -112,6 +134,21 @@ export class Timeline extends Writable {
|
||||
this.output.write(`${JSON.stringify(event)}\n`)
|
||||
}
|
||||
|
||||
// Input and terminal output share one monotonic clock. A sidecar leaves
|
||||
// the existing terminal timeline readable by older Drive releases.
|
||||
pointer(action: Pointer["action"], x: number, y: number) {
|
||||
if (this.writableEnded || this.destroyed) return
|
||||
if (!this.pointers) {
|
||||
this.pointers = createWriteStream(`${this.path.replace(/\.jsonl$/, "")}.pointers.jsonl`)
|
||||
this.pointers.on("error", (error) => this.destroy(error))
|
||||
}
|
||||
this.pointers.write(`${JSON.stringify({ atMs: this.elapsed(), action, x, y } satisfies Pointer)}\n`)
|
||||
}
|
||||
|
||||
private streams() {
|
||||
return this.pointers ? [this.output, this.pointers] : [this.output]
|
||||
}
|
||||
|
||||
private elapsed() {
|
||||
return Math.max(0, Math.round(performance.now() - this.started))
|
||||
}
|
||||
|
||||
@@ -103,6 +103,47 @@ test("clicks a target at relative coordinates through descendant text", async ()
|
||||
)
|
||||
})
|
||||
|
||||
test("mouse input drives native hover, drag, buttons and scrolling at absolute coordinates", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const renderer = yield* SimulationRenderer.create({})
|
||||
const events: Array<{ type: string; x: number; y: number; button: number }> = []
|
||||
const button = new BoxRenderable(renderer, {
|
||||
position: "absolute",
|
||||
left: 10,
|
||||
top: 5,
|
||||
width: 15,
|
||||
height: 3,
|
||||
onMouse: (event) => events.push({ type: event.type, x: event.x, y: event.y, button: event.button }),
|
||||
})
|
||||
renderer.root.add(button)
|
||||
const harness = createHarness(renderer)
|
||||
yield* Effect.promise(() => harness.renderOnce())
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 11, y: 6 } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 12, y: 6 } })
|
||||
expect(events.map((event) => event.type)).toContain("over")
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "move", x: 12, y: 6 }))
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "down", x: 12, y: 6, button: "right" } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 13, y: 6 } })
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "up", x: 13, y: 6, button: "right" } })
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "down", button: 2 }))
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "drag", x: 13, y: 6 }))
|
||||
expect(events).toContainEqual(expect.objectContaining({ type: "up", x: 13, y: 6, button: 2 }))
|
||||
expect(harness.mockMouse.getPressedButtons()).toEqual([])
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "scroll", x: 12, y: 6, direction: "down" } })
|
||||
expect(events.map((event) => event.type)).toContain("scroll")
|
||||
yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 1, y: 1 } })
|
||||
expect(events.map((event) => event.type)).toContain("out")
|
||||
const error = yield* execute(harness, { type: "ui.mouse", params: { action: "move", x: 100, y: 40 } }).pipe(
|
||||
Effect.flip,
|
||||
)
|
||||
expect(error.message).toContain("within the terminal viewport")
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects a semantic click when the live identity does not match", async () => {
|
||||
await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises"
|
||||
import { WriteStream } from "node:fs"
|
||||
import { once } from "node:events"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { TextRenderable } from "@opentui/core"
|
||||
import { createHarness, matches } from "../src/frontend/actions"
|
||||
import { SimulationRenderer } from "../src/frontend/renderer"
|
||||
import { Effect } from "effect"
|
||||
import { Timeline, type Event } from "../src/recording"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Timeline, Pointer, type Event } from "../src/recording"
|
||||
|
||||
test("streams ANSI chunks into a versioned JSONL timeline", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-recording-"))
|
||||
@@ -37,6 +39,71 @@ test("streams ANSI chunks into a versioned JSONL timeline", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("finishes the pointer sidecar on the output clock without changing the v1 timeline", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-pointer-recording-"))
|
||||
try {
|
||||
const path = join(directory, "timeline.jsonl")
|
||||
const timeline = await Timeline.create(path, 80, 24)
|
||||
timeline.write("before")
|
||||
timeline.pointer("move", 12, 5)
|
||||
timeline.pointer("click", 15, 6)
|
||||
timeline.write("after")
|
||||
const first = timeline.finish()
|
||||
expect(timeline.finish()).toBe(first)
|
||||
expect(await first).toBe(path)
|
||||
timeline.pointer("move", 30, 10)
|
||||
const pointers = (await Bun.file(join(directory, "timeline.pointers.jsonl")).text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => Schema.decodeUnknownSync(Schema.fromJsonString(Pointer))(line))
|
||||
expect(pointers.map(({ action, x, y }) => ({ action, x, y }))).toEqual([
|
||||
{ action: "move", x: 12, y: 5 },
|
||||
{ action: "click", x: 15, y: 6 },
|
||||
])
|
||||
const output = (await Bun.file(path).text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line) as Event)
|
||||
const firstOutput = output[1]
|
||||
const lastOutput = output.at(-1)
|
||||
if (firstOutput?.type !== "output" || lastOutput?.type !== "output") throw new Error("missing output")
|
||||
expect(pointers[0]?.atMs).toBeGreaterThanOrEqual(firstOutput.at_ms)
|
||||
expect(pointers[1]?.atMs).toBeLessThanOrEqual(lastOutput.at_ms)
|
||||
expect(output.every((event) => ["header", "output", "resize"].includes(event.type))).toBe(true)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test.each(["pointer", "output"])("joins both recording streams after an early %s failure", async (failed) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-pointer-failure-"))
|
||||
try {
|
||||
const timeline = await Timeline.create(join(directory, "timeline.jsonl"), 80, 24)
|
||||
if (failed === "pointer") await mkdir(join(directory, "timeline.pointers.jsonl"))
|
||||
const error = new Promise<Error>((resolve) => timeline.once("error", resolve))
|
||||
timeline.pointer("move", 10, 5)
|
||||
const output: unknown = Reflect.get(timeline, "output")
|
||||
const pointers: unknown = Reflect.get(timeline, "pointers")
|
||||
if (!(output instanceof WriteStream) || !(pointers instanceof WriteStream)) throw new Error("missing owned streams")
|
||||
if (failed === "output") {
|
||||
if (pointers.pending) await once(pointers, "open")
|
||||
output.destroy(new Error("output failed"))
|
||||
}
|
||||
const failure = await error
|
||||
const finishing = timeline.finish()
|
||||
expect(timeline.finish()).toBe(finishing)
|
||||
await expect(finishing).rejects.toBe(failure)
|
||||
expect(output.closed).toBe(true)
|
||||
expect(pointers.closed).toBe(true)
|
||||
expect(Reflect.get(output, "fd")).toBeNull()
|
||||
expect(Reflect.get(pointers, "fd")).toBeNull()
|
||||
timeline.pointer("move", 99, 99)
|
||||
expect(timeline.finish()).toBe(finishing)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("captures native renderer output and finishes on destroy", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "simulation-renderer-recording-"))
|
||||
const path = join(directory, "timeline.jsonl")
|
||||
|
||||
@@ -99,11 +99,15 @@ export function DialogModel(props: { providerID?: string }) {
|
||||
return false
|
||||
return true
|
||||
}),
|
||||
connected(),
|
||||
)
|
||||
|
||||
if (needle) {
|
||||
return prioritizeFavorites(
|
||||
fuzzysort.go(needle, modelOptions, { keys: ["title", "category"] }).map((item) => item.obj),
|
||||
sortModelOptions(
|
||||
fuzzysort.go(needle, modelOptions, { keys: ["title", "category"] }).map((item) => item.obj),
|
||||
false,
|
||||
),
|
||||
favoritePriority,
|
||||
)
|
||||
}
|
||||
@@ -179,15 +183,24 @@ export function prioritizeFavorites<T extends { value: { providerID: string; mod
|
||||
}
|
||||
|
||||
export function sortModelOptions<
|
||||
T extends { providerID?: string; providerName?: string; releaseDate: string | number; title: string },
|
||||
>(options: T[]) {
|
||||
T extends {
|
||||
providerID?: string
|
||||
providerName?: string
|
||||
releaseDate: string | number
|
||||
title: string
|
||||
footer?: string
|
||||
},
|
||||
>(options: T[], grouped = true) {
|
||||
return options.toSorted((a, b) => {
|
||||
const provider = Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode")
|
||||
const provider = grouped ? Number(a.providerID !== "opencode") - Number(b.providerID !== "opencode") : 0
|
||||
if (provider !== 0) return provider
|
||||
|
||||
const name = (a.providerName ?? "").localeCompare(b.providerName ?? "")
|
||||
const name = grouped ? (a.providerName ?? "").localeCompare(b.providerName ?? "") : 0
|
||||
if (name !== 0) return name
|
||||
|
||||
const free = Number(b.footer === "Free") - Number(a.footer === "Free")
|
||||
if (free !== 0) return free
|
||||
|
||||
const release = Number(b.releaseDate) - Number(a.releaseDate)
|
||||
if (release !== 0) return release
|
||||
|
||||
|
||||
@@ -87,7 +87,6 @@ export function Autocomplete(props: {
|
||||
index: 0,
|
||||
selected: 0,
|
||||
visible: false as AutocompleteRef["visible"],
|
||||
input: "keyboard" as "keyboard" | "mouse",
|
||||
})
|
||||
|
||||
const [positionTick, setPositionTick] = createSignal(0)
|
||||
@@ -151,14 +150,6 @@ export function Autocomplete(props: {
|
||||
setSearch(next ? next : "")
|
||||
})
|
||||
|
||||
// When the filter changes due to how TUI works, the mousemove might still be triggered
|
||||
// via a synthetic event as the layout moves underneath the cursor. This is a workaround to make sure the input mode remains keyboard so
|
||||
// that the mouseover event doesn't trigger when filtering.
|
||||
createEffect(() => {
|
||||
filter()
|
||||
setStore("input", "keyboard")
|
||||
})
|
||||
|
||||
function insertPart(
|
||||
text: string,
|
||||
part:
|
||||
@@ -724,7 +715,6 @@ export function Autocomplete(props: {
|
||||
title: "Previous autocomplete item",
|
||||
group: "Autocomplete",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-1)
|
||||
},
|
||||
},
|
||||
@@ -733,7 +723,6 @@ export function Autocomplete(props: {
|
||||
title: "Next autocomplete item",
|
||||
group: "Autocomplete",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(1)
|
||||
},
|
||||
},
|
||||
@@ -942,17 +931,8 @@ export function Autocomplete(props: {
|
||||
: undefined
|
||||
}
|
||||
flexDirection="row"
|
||||
onMouseMove={() => {
|
||||
setStore("input", "mouse")
|
||||
}}
|
||||
onMouseOver={() => {
|
||||
if (store.input !== "mouse") return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseDown={() => {
|
||||
setStore("input", "mouse")
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseMove={() => moveTo(index)}
|
||||
onMouseDown={() => moveTo(index)}
|
||||
onMouseUp={() => select()}
|
||||
>
|
||||
<text
|
||||
|
||||
@@ -438,7 +438,7 @@ export function RunFormBody(props: {
|
||||
flexDirection="row"
|
||||
gap={1}
|
||||
alignItems="flex-start"
|
||||
onMouseOver={() => setState((previous) => formSetSelected(previous, index()))}
|
||||
onMouseMove={() => setState((previous) => formSetSelected(previous, index()))}
|
||||
backgroundColor={active() ? props.theme.formfieldFocusedBg : "transparent"}
|
||||
onMouseUp={() => choose(index())}
|
||||
>
|
||||
|
||||
@@ -54,7 +54,7 @@ function buttons(
|
||||
paddingLeft={1}
|
||||
paddingRight={1}
|
||||
backgroundColor={option === selected ? theme.actionFocusedBg : transparent}
|
||||
onMouseOver={() => {
|
||||
onMouseMove={() => {
|
||||
if (!disabled) onHover(option)
|
||||
}}
|
||||
onMouseUp={() => {
|
||||
|
||||
@@ -125,7 +125,7 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
backgroundColor={
|
||||
active() ? theme.background.action.primary.focused : theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", index())}
|
||||
onMouseMove={() => setStore("selected", index())}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", index())
|
||||
open()
|
||||
|
||||
@@ -215,7 +215,7 @@ export function SubagentsTab(props: { sessionID: string }) {
|
||||
? theme.background.action.primary.selected
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", index())}
|
||||
onMouseMove={() => setStore("selected", index())}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", index())
|
||||
navigate({ type: "session", sessionID: entry.sessionID })
|
||||
|
||||
@@ -84,7 +84,7 @@ export function TerminalsTab(props: { sessionID: string; visibleTerminalID?: str
|
||||
? theme.background.action.primary.selected
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setSelected(index())}
|
||||
onMouseMove={() => setSelected(index())}
|
||||
onMouseUp={() => {
|
||||
setSelected(index())
|
||||
select()
|
||||
|
||||
@@ -907,7 +907,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
||||
}
|
||||
return (
|
||||
<box
|
||||
onMouseOver={() => setStore("selected", i())}
|
||||
onMouseMove={() => setStore("selected", i())}
|
||||
onMouseDown={() => setStore("selected", i())}
|
||||
onMouseUp={() => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return
|
||||
@@ -961,7 +961,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
||||
</For>
|
||||
<Show when={custom()}>
|
||||
<box
|
||||
onMouseOver={() => setStore("selected", rows().length)}
|
||||
onMouseMove={() => setStore("selected", rows().length)}
|
||||
onMouseDown={() => setStore("selected", rows().length)}
|
||||
onMouseUp={() => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return
|
||||
|
||||
@@ -591,7 +591,7 @@ export function SessionQuestion<const T extends Record<string, string>>(props: {
|
||||
? theme.background.action.primary.focused
|
||||
: theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setStore("selected", option)}
|
||||
onMouseMove={() => setStore("selected", option)}
|
||||
onMouseUp={() => {
|
||||
setStore("selected", option)
|
||||
props.onSelect(option)
|
||||
|
||||
@@ -112,7 +112,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
const [store, setStore] = createStore({
|
||||
selected: 0,
|
||||
filter: "",
|
||||
input: "keyboard" as "keyboard" | "mouse",
|
||||
})
|
||||
const [focusedAction, setFocusedAction] = createSignal<number>()
|
||||
const actionFocused = createMemo(() => focusedAction() !== undefined)
|
||||
@@ -201,12 +200,8 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
return result
|
||||
})
|
||||
|
||||
// When the filter changes due to how TUI works, the mousemove might still be triggered
|
||||
// via a synthetic event as the layout moves underneath the cursor. This is a workaround to make sure the input mode remains keyboard
|
||||
// that the mouseover event doesn't trigger when filtering.
|
||||
createEffect(() => {
|
||||
filtered()
|
||||
setStore("input", "keyboard")
|
||||
setFocusedAction(undefined)
|
||||
})
|
||||
|
||||
@@ -384,7 +379,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
|
||||
function submit() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
const index = focusedAction()
|
||||
if (index !== undefined) {
|
||||
trigger(actionItems()[index])
|
||||
@@ -418,7 +412,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Previous item",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-1)
|
||||
},
|
||||
},
|
||||
@@ -427,7 +420,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Next item",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(1)
|
||||
},
|
||||
},
|
||||
@@ -436,7 +428,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Page up",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(-10)
|
||||
},
|
||||
},
|
||||
@@ -445,7 +436,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
title: "Page down",
|
||||
group: "Dialog",
|
||||
run() {
|
||||
setStore("input", "keyboard")
|
||||
move(10)
|
||||
},
|
||||
},
|
||||
@@ -455,7 +445,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
group: "Dialog",
|
||||
run() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
moveTo(0)
|
||||
},
|
||||
},
|
||||
@@ -465,7 +454,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
group: "Dialog",
|
||||
run() {
|
||||
if (props.locked) return
|
||||
setStore("input", "keyboard")
|
||||
moveTo(flat().length - 1)
|
||||
},
|
||||
},
|
||||
@@ -538,7 +526,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
|
||||
function trigger(item: Action | undefined) {
|
||||
if (props.locked || !item || isActionDisabled(item)) return
|
||||
setStore("input", "keyboard")
|
||||
if (item.selection === "none") {
|
||||
item.onTrigger()
|
||||
return
|
||||
@@ -709,21 +696,16 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
position="relative"
|
||||
onMouseMove={() => {
|
||||
if (props.locked) return
|
||||
setStore("input", "mouse")
|
||||
setFocusedAction(undefined)
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
if (index === -1 || index === store.selected) return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseUp={() => {
|
||||
if (props.locked) return
|
||||
option.onSelect?.(dialog)
|
||||
props.onSelect?.(option)
|
||||
}}
|
||||
onMouseOver={() => {
|
||||
if (props.locked) return
|
||||
if (store.input !== "mouse") return
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
if (index === -1) return
|
||||
moveTo(index)
|
||||
}}
|
||||
onMouseDown={() => {
|
||||
if (props.locked) return
|
||||
const index = flat().findIndex((x) => isDeepEqual(x.value, option.value))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { go } from "fuzzysort"
|
||||
import { prioritizeFavorites, sortModelOptions } from "../../../../src/component/dialog-model"
|
||||
|
||||
describe("prioritizeFavorites", () => {
|
||||
@@ -23,6 +24,20 @@ describe("prioritizeFavorites", () => {
|
||||
})
|
||||
|
||||
describe("sortModelOptions", () => {
|
||||
test.each(["browse", "search", "provider"])("orders %s results free-first, then newest-first", (mode) => {
|
||||
const options = [
|
||||
{ providerID: "opencode", title: "Claude Haiku 3", releaseDate: 1 },
|
||||
{ providerID: "anthropic", title: "Claude Haiku 4.5", releaseDate: 2 },
|
||||
{ providerID: "anthropic", title: "Claude Haiku Free", releaseDate: 0, footer: "Free" },
|
||||
].map((item) => ({ ...item, providerID: mode === "provider" ? "anthropic" : item.providerID }))
|
||||
const matches = mode === "search" ? go("haik", options, { key: "title" }).map((item) => item.obj) : options
|
||||
expect(sortModelOptions(matches, mode === "provider").map((item) => item.title)).toEqual([
|
||||
"Claude Haiku Free",
|
||||
"Claude Haiku 4.5",
|
||||
"Claude Haiku 3",
|
||||
])
|
||||
})
|
||||
|
||||
test("orders opencode models before other providers", () => {
|
||||
const sorted = sortModelOptions([
|
||||
{ providerID: "openai", providerName: "OpenAI", releaseDate: 3, title: "GPT 5" },
|
||||
|
||||
@@ -104,6 +104,7 @@ const source = {
|
||||
"ui.messagePart.review.title": "Review your answers",
|
||||
"ui.messagePart.questions.dismissed": "Questions dismissed",
|
||||
"ui.messagePart.compaction": "Session compacted",
|
||||
"ui.messagePart.context.details": "Details",
|
||||
"ui.messagePart.context.read.one": "{{count}} read",
|
||||
"ui.messagePart.context.read.other": "{{count}} reads",
|
||||
"ui.messagePart.context.search.one": "{{count}} search",
|
||||
@@ -133,7 +134,10 @@ const source = {
|
||||
|
||||
"ui.promptInput.noMatchingItems": "No matching items",
|
||||
"ui.promptInput.commands": "Commands",
|
||||
"ui.promptInput.dropFiles": "Drop files to attach",
|
||||
"ui.promptInput.dropFiles": "Drop files to add",
|
||||
"ui.promptInput.dropFiles.image": "Drop images or files to add",
|
||||
"ui.promptInput.dropFiles.pdf": "Drop PDFs or files to add",
|
||||
"ui.promptInput.dropFiles.imagePdf": "Drop images, PDFs, or files to add",
|
||||
"ui.promptInput.removeAttachment": "Remove attachment",
|
||||
"ui.promptInput.label": "Prompt",
|
||||
"ui.promptInput.placeholder.shell": "Enter shell command…",
|
||||
|
||||
@@ -1104,7 +1104,8 @@ effect: (ctx) =>
|
||||
}),
|
||||
```
|
||||
|
||||
Modify model request settings and optionally scope the hook to one provider.
|
||||
Modify model request settings and optionally scope the hook to one provider. The event carries the same `kind` as
|
||||
the HTTP hooks below.
|
||||
|
||||
```ts
|
||||
effect: (ctx) =>
|
||||
@@ -1119,14 +1120,18 @@ effect: (ctx) =>
|
||||
```
|
||||
|
||||
Modify native provider requests or responses. Their bodies are one-shot streams; clone or replace a body before reading
|
||||
it.
|
||||
it. Both hooks run for every request a session issues; `event.kind` is `"primary"`, `"compaction"`, `"title"`, or
|
||||
`"generate"` depending on which flow issued it.
|
||||
|
||||
```ts
|
||||
effect: (ctx) =>
|
||||
Effect.gen(function* () {
|
||||
const session = ctx.session
|
||||
yield* session.hook("http.request", (event) =>
|
||||
Effect.sync(() => event.request.headers.set("x-session-id", event.sessionID)),
|
||||
Effect.sync(() => {
|
||||
event.request.headers.set("x-session-id", event.sessionID)
|
||||
if (event.kind === "title") event.request.headers.set("x-priority", "background")
|
||||
}),
|
||||
)
|
||||
yield* session.hook("http.response", (event) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -1139,7 +1139,8 @@ Generation options depend on the selected protocol and model:
|
||||
|
||||
#### Model request
|
||||
|
||||
Modify model request settings and optionally scope the hook to one provider.
|
||||
Modify model request settings and optionally scope the hook to one provider. The event carries the same `kind`
|
||||
as the HTTP hooks below.
|
||||
|
||||
```ts
|
||||
await ctx.session.hook(
|
||||
@@ -1156,9 +1157,14 @@ await ctx.session.hook(
|
||||
Modify native provider requests or responses. Their bodies are one-shot streams; clone or replace a body before reading
|
||||
it.
|
||||
|
||||
Both hooks run for every request a session issues. `event.kind` says which flow issued it: `"primary"` for the agent
|
||||
loop, `"compaction"` for checkpoint summaries, `"title"` for title generation, and `"generate"` for transient
|
||||
`ctx.session.generate` calls. Use it instead of the agent ID to tell auxiliary requests apart.
|
||||
|
||||
```ts
|
||||
await ctx.session.hook("http.request", (event) => {
|
||||
event.request.headers.set("x-session-id", event.sessionID)
|
||||
if (event.kind === "title") event.request.headers.set("x-priority", "background")
|
||||
})
|
||||
|
||||
await ctx.session.hook("http.response", (event) => {
|
||||
|
||||
Reference in New Issue
Block a user