mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(core): reject malformed tool arguments and settle unfinished calls
This commit is contained in:
parent
34cf183c4c
commit
600c40e1b8
8 changed files with 217 additions and 34 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import { Effect, Option } from "effect"
|
||||
import { AIError, LLMEvent, type ProviderMetadata, type ToolCall } from "../../schema/index.js"
|
||||
import { AIError, LLMEvent, type ProviderMetadata, type ToolCall, type ToolInputError } from "../../schema/index.js"
|
||||
import { eventError, parseToolInput, type ToolAccumulator } from "../shared.js"
|
||||
import { parse } from "./partial-json.js"
|
||||
|
||||
|
|
@ -79,16 +79,6 @@ const inputDelta = (tool: PendingTool, text: string): LLMEvent => {
|
|||
const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
||||
const raw = inputOverride ?? tool.input
|
||||
return parseToolInput(route, tool.name, raw).pipe(
|
||||
Effect.catch((error) =>
|
||||
tool.providerExecuted
|
||||
? Effect.fail(error)
|
||||
: Effect.succeed(
|
||||
Option.getOrElse(
|
||||
Option.map(parsePartialInput(raw), (input) => input ?? {}),
|
||||
() => ({}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(input): ToolCall =>
|
||||
LLMEvent.toolCall({
|
||||
|
|
@ -100,10 +90,15 @@ const toolCall = (route: string, tool: PendingTool, inputOverride?: string) => {
|
|||
providerMetadata: tool.providerMetadata,
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
tool.providerExecuted
|
||||
? Effect.fail(error)
|
||||
: Effect.succeed(LLMEvent.toolInputError({ id: tool.id, name: tool.name, namespace: tool.namespace, raw })),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const finishEvents = (tool: PendingTool, event: ToolCall): ReadonlyArray<LLMEvent> => [
|
||||
const finishEvents = (tool: PendingTool, event: ToolCall | ToolInputError): ReadonlyArray<LLMEvent> => [
|
||||
LLMEvent.toolInputEnd({
|
||||
id: tool.id,
|
||||
name: tool.name,
|
||||
|
|
@ -206,7 +201,7 @@ export const appendExisting = <K extends StreamKey>(
|
|||
|
||||
/**
|
||||
* Finalize one pending tool call: parse the accumulated raw JSON, remove it
|
||||
* from state, and recover incomplete local arguments when needed.
|
||||
* from state, and reject malformed local arguments without repairing them.
|
||||
* Missing keys are a no-op because some providers emit stop events for
|
||||
* non-tool content blocks.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1929,6 +1929,44 @@ describe("Anthropic Messages route", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
for (const stopReason of ["tool_use", "max_tokens", "refusal"]) {
|
||||
it.effect(`rejects incomplete local tool input before ${stopReason}`, () =>
|
||||
Effect.gen(function* () {
|
||||
const raw = '{"query":"partial'
|
||||
const response = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(
|
||||
sseEvents(
|
||||
{ type: "message_start", message: { usage: { input_tokens: 5 } } },
|
||||
{
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: { type: "tool_use", id: "call_1", name: "lookup" },
|
||||
},
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: raw } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: stopReason }, usage: { output_tokens: 1 } },
|
||||
{ type: "message_stop" },
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
expect(response.toolCalls).toEqual([])
|
||||
expect(response.events.find((event) => event.type === "tool-input-delta")).toMatchObject({
|
||||
text: raw,
|
||||
input: { query: "partial" },
|
||||
})
|
||||
expect(response.events.find((event) => event.type === "tool-input-error")).toEqual({
|
||||
type: "tool-input-error",
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
raw,
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
it.effect("keeps malformed server tool input terminal", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
|
|
|
|||
|
|
@ -1131,7 +1131,7 @@ describe("Bedrock Converse route", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers incomplete tool input at finalization", () =>
|
||||
it.effect("rejects incomplete tool input at finalization", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
["messageStart", { role: "assistant" }],
|
||||
|
|
@ -1148,10 +1148,11 @@ describe("Bedrock Converse route", () => {
|
|||
)
|
||||
const response = yield* LLMClient.generate(baseRequest).pipe(Effect.provide(fixedBytes(body)))
|
||||
|
||||
expect(response.events.find((event) => event.type === "tool-call")).toMatchObject({
|
||||
expect(response.toolCalls).toEqual([])
|
||||
expect(response.events.find((event) => event.type === "tool-input-error")).toMatchObject({
|
||||
id: "tool_1",
|
||||
name: "lookup",
|
||||
input: { query: "partial" },
|
||||
raw: '{"query":"partial',
|
||||
})
|
||||
expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "end_turn" })
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -4505,7 +4505,7 @@ describe("OpenAI Responses route", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers authoritative incomplete final function arguments", () =>
|
||||
it.effect("rejects authoritative incomplete final function arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
|
|
@ -4531,17 +4531,17 @@ describe("OpenAI Responses route", () => {
|
|||
}),
|
||||
).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({
|
||||
expect(response.toolCalls).toEqual([])
|
||||
expect(response.events.find(LLMEvent.is.toolInputError)).toMatchObject({
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
input: { query: "partial" },
|
||||
raw: '{"query":"partial',
|
||||
})
|
||||
expect(response.finishReason.normalized).toBe("tool-calls")
|
||||
expect(response.events.some(LLMEvent.is.toolInputError)).toBeFalse()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers incomplete function arguments when output_item.added is absent", () =>
|
||||
it.effect("rejects incomplete function arguments when output_item.added is absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = sseEvents(
|
||||
{
|
||||
|
|
@ -4558,10 +4558,11 @@ describe("OpenAI Responses route", () => {
|
|||
)
|
||||
const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
|
||||
|
||||
expect(response.events.find(LLMEvent.is.toolCall)).toMatchObject({
|
||||
expect(response.toolCalls).toEqual([])
|
||||
expect(response.events.find(LLMEvent.is.toolInputError)).toMatchObject({
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
input: { query: "partial" },
|
||||
raw: '{"query":"partial',
|
||||
})
|
||||
expect(response.finishReason.normalized).toBe("tool-calls")
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -126,7 +126,7 @@ describe("ToolStream", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("finalizes incomplete local input using the partial JSON parser", () =>
|
||||
it.effect("rejects incomplete final local input", () =>
|
||||
Effect.gen(function* () {
|
||||
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||
id: "call_1",
|
||||
|
|
@ -139,13 +139,44 @@ describe("ToolStream", () => {
|
|||
tools: {},
|
||||
events: [
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "partial" } },
|
||||
{ type: "tool-input-error", id: "call_1", name: "lookup", raw: '{"query":"partial' },
|
||||
],
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("repairs malformed string escapes in final local input", () =>
|
||||
it.effect("rejects malformed authoritative input instead of using valid deltas", () =>
|
||||
Effect.gen(function* () {
|
||||
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||
id: "call_1",
|
||||
name: "lookup",
|
||||
input: '{"query":"weather"}',
|
||||
})
|
||||
const finished = yield* ToolStream.finishWithInput(ADAPTER, tools, "item_1", '{"query":"partial')
|
||||
|
||||
expect(finished).toEqual({
|
||||
tools: {},
|
||||
events: [
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-input-error", id: "call_1", name: "lookup", raw: '{"query":"partial' },
|
||||
],
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("preserves empty input for zero-argument tools", () =>
|
||||
Effect.gen(function* () {
|
||||
const tools = ToolStream.start(ToolStream.empty<number>(), 0, { id: "call_1", name: "lookup" })
|
||||
const finished = yield* ToolStream.finish(ADAPTER, tools, 0)
|
||||
|
||||
expect(finished.events).toEqual([
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_1", name: "lookup", input: {} },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects malformed string escapes in final local input", () =>
|
||||
Effect.gen(function* () {
|
||||
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||
id: "call_1",
|
||||
|
|
@ -156,12 +187,12 @@ describe("ToolStream", () => {
|
|||
|
||||
expect(finished.events).toEqual([
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_1", name: "lookup", input: { path: "A\\H", text: "first\tsecond" } },
|
||||
{ type: "tool-input-error", id: "call_1", name: "lookup", raw: '{"path":"A\\H","text":"first\tsecond"}' },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("defaults unrecoverable local input to an empty object", () =>
|
||||
it.effect("rejects invalid final local input instead of defaulting to an empty object", () =>
|
||||
Effect.gen(function* () {
|
||||
const tools = ToolStream.start(ToolStream.empty<string>(), "item_1", {
|
||||
id: "call_1",
|
||||
|
|
@ -172,12 +203,12 @@ describe("ToolStream", () => {
|
|||
|
||||
expect(finished.events).toEqual([
|
||||
{ type: "tool-input-end", id: "call_1", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_1", name: "lookup", input: {} },
|
||||
{ type: "tool-input-error", id: "call_1", name: "lookup", raw: "invalid" },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("recovers incomplete input alongside valid parallel tool calls", () =>
|
||||
it.effect("rejects incomplete input without dropping valid parallel tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const valid = ToolStream.start(ToolStream.empty<number>(), 0, {
|
||||
id: "call_valid",
|
||||
|
|
@ -197,7 +228,7 @@ describe("ToolStream", () => {
|
|||
{ type: "tool-input-end", id: "call_valid", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_valid", name: "lookup", input: { query: "weather" } },
|
||||
{ type: "tool-input-end", id: "call_invalid", name: "lookup" },
|
||||
{ type: "tool-call", id: "call_invalid", name: "lookup", input: { query: "partial" } },
|
||||
{ type: "tool-input-error", id: "call_invalid", name: "lookup", raw: '{"query":"partial' },
|
||||
],
|
||||
})
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -395,7 +395,7 @@ export const createLLMEventPublisher = (bus: Pick<Bus.Interface, "publish">, inp
|
|||
})
|
||||
|
||||
const failUnsettledTools = Effect.fn("SessionRunner.failUnsettledTools")(
|
||||
(error: SessionError.Error, scope: "hosted" | "all" = "all") => failTools(error, scope),
|
||||
(error: SessionError.Error, scope: "hosted" | "all" | "uncalled" = "all") => failTools(error, scope),
|
||||
)
|
||||
|
||||
const publish = Effect.fnUntraced(function* (event: LLMEvent) {
|
||||
|
|
|
|||
|
|
@ -61,6 +61,11 @@ interface Input {
|
|||
const TOOLS_INTERRUPTED = { type: "aborted", message: "Tool execution interrupted" } as const
|
||||
const STEP_INTERRUPTED = { type: "aborted", message: "Step interrupted" } as const
|
||||
const RESULT_MISSING = { type: "tool.result-missing", message: "Provider did not return a tool result" } as const
|
||||
const INPUT_INCOMPLETE = {
|
||||
type: "tool.input-incomplete",
|
||||
message:
|
||||
"Tool call arguments were not completed and were not executed. Re-issue the tool call with complete arguments.",
|
||||
} as const
|
||||
|
||||
/** Captures Location-scoped dependencies without introducing another service or execution loop. */
|
||||
export const make = Effect.gen(function* () {
|
||||
|
|
@ -216,10 +221,11 @@ export const make = Effect.gen(function* () {
|
|||
if (toolFailure) yield* publisher.failUnsettledTools(toolFailure)
|
||||
if (interrupted) yield* publisher.failAssistant(STEP_INTERRUPTED)
|
||||
|
||||
// All local fibers have joined; only provider-hosted results can still be missing.
|
||||
// Parsers may leave unfinished calls without an execution event.
|
||||
if (llmError || (Exit.isSuccess(stream) && !recorded.providerFailed)) {
|
||||
const missing = yield* publisher.failUnsettledTools(RESULT_MISSING, "hosted")
|
||||
if (missing && !llmError && !recorded.finish) yield* publisher.failAssistant(RESULT_MISSING)
|
||||
yield* publisher.failUnsettledTools(INPUT_INCOMPLETE, "uncalled")
|
||||
}
|
||||
|
||||
const record = publisher.record()
|
||||
|
|
|
|||
|
|
@ -845,7 +845,16 @@ const fragmentFixture = (kind: FragmentKind, id: string, chunks: readonly string
|
|||
return {
|
||||
partialEvents,
|
||||
completeEvents: [...partialEvents, LLMEvent.toolInputEnd({ id, name: "echo" })],
|
||||
expectedAssistant: { type: "assistant", content: [expectedContent] },
|
||||
expectedAssistant: {
|
||||
type: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool",
|
||||
id,
|
||||
state: { status: "error", input: {}, error: { type: "tool.input-incomplete" } },
|
||||
},
|
||||
],
|
||||
},
|
||||
expectedContent,
|
||||
}
|
||||
}
|
||||
|
|
@ -3712,6 +3721,45 @@ describe("SessionRunnerLLM", () => {
|
|||
expect(systemTexts(s.requests[1])).toContain("Replacement context")
|
||||
})
|
||||
|
||||
scenario("executes a completed tool call before the provider finishes the response", function* (s) {
|
||||
yield* s.admit("Echo this")
|
||||
const tools = yield* s.blockTools()
|
||||
const finish = yield* Deferred.make<void>()
|
||||
yield* s.llm.push(
|
||||
Stream.fromIterable([
|
||||
LLMEvent.stepStart({ index: 0 }),
|
||||
LLMEvent.toolInputStart({ id: "call-early", name: "echo" }),
|
||||
LLMEvent.toolInputDelta({ id: "call-early", name: "echo", text: '{"text":"hello"}' }),
|
||||
LLMEvent.toolInputEnd({ id: "call-early", name: "echo" }),
|
||||
LLMEvent.toolCall({ id: "call-early", name: "echo", input: { text: "hello" } }),
|
||||
]).pipe(
|
||||
Stream.concat(
|
||||
Stream.fromEffect(Deferred.await(finish)).pipe(
|
||||
Stream.flatMap(() =>
|
||||
Stream.fromIterable([
|
||||
LLMEvent.stepFinish({ index: 0, reason: { normalized: "tool-calls" } }),
|
||||
LLMEvent.finish({ reason: { normalized: "tool-calls" } }),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
TestLLM.stop(),
|
||||
)
|
||||
const run = yield* s.resume.pipe(Effect.forkChild)
|
||||
yield* tools.started
|
||||
|
||||
expect(requireAssistant(yield* s.context)).toMatchObject({
|
||||
content: [{ type: "tool", id: "call-early", state: { status: "running", input: { text: "hello" } } }],
|
||||
})
|
||||
expect(yield* recordedEventTypes(sessionID)).not.toContain("session.step.streamed.1")
|
||||
|
||||
yield* Deferred.succeed(finish, undefined)
|
||||
yield* tools.release
|
||||
yield* Fiber.join(run)
|
||||
expect(s.executions).toEqual(["hello"])
|
||||
})
|
||||
|
||||
scenario("consumes the full provider stream before recording its boundary and settling local tools", function* (s) {
|
||||
yield* s.admit("Echo this")
|
||||
const request = yield* s.llm.gate
|
||||
|
|
@ -6023,6 +6071,69 @@ describe("SessionRunnerLLM", () => {
|
|||
])
|
||||
})
|
||||
|
||||
for (const finish of ["stop", "length"] as const) {
|
||||
for (const ended of [false, true]) {
|
||||
scenario(`settles unfinished tool input after ${finish} (input ended: ${ended})`, function* (s) {
|
||||
const raw = '{"text":"unfinished-marker'
|
||||
yield* s.llm.push(
|
||||
TestLLM.complete(
|
||||
{ reason: { normalized: finish } },
|
||||
LLMEvent.toolCall({ id: "call-valid", name: "echo", input: { text: "valid" } }),
|
||||
LLMEvent.toolInputStart({ id: "call-incomplete", name: "echo" }),
|
||||
LLMEvent.toolInputDelta({ id: "call-incomplete", name: "echo", text: raw }),
|
||||
...(ended ? [LLMEvent.toolInputEnd({ id: "call-incomplete", name: "echo" })] : []),
|
||||
),
|
||||
TestLLM.stop(),
|
||||
)
|
||||
|
||||
yield* s.runPrompt("Recover unfinished tool input")
|
||||
|
||||
expect(s.requests).toHaveLength(2)
|
||||
expect(s.executions).toEqual(["valid"])
|
||||
expect(JSON.stringify(s.requests[1])).not.toContain("unfinished-marker")
|
||||
expect(s.requests[1]?.messages).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
role: "tool",
|
||||
content: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "tool-result",
|
||||
id: "call-incomplete",
|
||||
result: expect.objectContaining({ type: "error" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
)
|
||||
const assistant = requireAssistant(yield* s.context)
|
||||
expect(assistant.error).toBeUndefined()
|
||||
expect(assistant.content).toMatchObject([
|
||||
{ type: "tool", id: "call-valid", state: { status: "completed" } },
|
||||
{
|
||||
type: "tool",
|
||||
id: "call-incomplete",
|
||||
executed: false,
|
||||
state: { status: "error", error: { type: "tool.input-incomplete" } },
|
||||
},
|
||||
])
|
||||
const events = yield* s.db
|
||||
.select({ type: EventTable.type, data: EventTable.data })
|
||||
.from(EventTable)
|
||||
.where(eq(EventTable.aggregate_id, sessionID))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
expect(
|
||||
events.filter((event) => event.type === "session.tool.input.ended.1" && event.data.id === "call-incomplete"),
|
||||
).toHaveLength(1)
|
||||
expect(
|
||||
events.filter((event) => event.type === "session.tool.failed.2" && event.data.id === "call-incomplete"),
|
||||
).toHaveLength(1)
|
||||
yield* replaySessionProjection(sessionID)
|
||||
expect((yield* s.context).find((message) => message.id === assistant.id)).toEqual(assistant)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
scenario("continues after malformed local tool input without exposing raw arguments", function* (s) {
|
||||
const marker = "raw-malformed-marker"
|
||||
const raw = `{"text":"${marker}`
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue