Skip to content
3 changes: 3 additions & 0 deletions packages/opencode/src/session/compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const Event = {
export const PRUNE_MINIMUM = 20_000
export const PRUNE_PROTECT = 40_000
const TOOL_OUTPUT_MAX_CHARS = 2_000
const TOOL_INPUT_MAX_CHARS = 2_000
const PRUNE_PROTECTED_TOOLS = ["skill"]
const DEFAULT_TAIL_TURNS = 2
const MIN_PRESERVE_RECENT_TOKENS = 2_000
Expand Down Expand Up @@ -252,6 +253,7 @@ export const layer: Layer.Layer<
const msgs = yield* MessageV2.toModelMessagesEffect(input.messages, input.model, {
stripMedia: true,
toolOutputMaxChars: TOOL_OUTPUT_MAX_CHARS,
toolInputMaxChars: TOOL_INPUT_MAX_CHARS,
})
return Token.estimate(JSON.stringify(msgs))
})
Expand Down Expand Up @@ -497,6 +499,7 @@ export const layer: Layer.Layer<
const modelMessages = yield* MessageV2.toModelMessagesEffect(msgs, model, {
stripMedia: true,
toolOutputMaxChars: TOOL_OUTPUT_MAX_CHARS,
toolInputMaxChars: TOOL_INPUT_MAX_CHARS,
})
const processor = yield* processors.create({
assistantMessage: msg,
Expand Down
33 changes: 27 additions & 6 deletions packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ function truncateToolOutput(text: string, maxChars?: number) {
return `${text.slice(0, sliceLen)}${suffixTemplate(omitted)}`
}

function truncateToolInputString(text: string, maxChars?: number) {
if (maxChars == null || text.length <= maxChars) return text
if (maxChars <= 0) return ""
const suffixTemplate = (n: number) => `\n[Tool input truncated for compaction: omitted ${n} chars]`
const reserve = suffixTemplate(text.length).length
if (reserve >= maxChars) return text.slice(0, maxChars)
const sliceLen = Math.max(0, maxChars - reserve)
const omitted = text.length - sliceLen
return `${text.slice(0, sliceLen)}${suffixTemplate(omitted)}`
}

function truncateToolInput(input: unknown, maxChars?: number): unknown {
if (maxChars == null) return input
if (typeof input === "string") return truncateToolInputString(input, maxChars)
if (Array.isArray(input)) return input.map((item) => truncateToolInput(item, maxChars))
if (!input || typeof input !== "object") return input
return Object.fromEntries(
Object.entries(input as Record<string, unknown>).map(([key, value]) => [key, truncateToolInput(value, maxChars)]),
)
}

/** Error shape thrown by Bun's fetch() when gzip/br decompression fails mid-stream */
interface FetchDecompressionError extends Error {
code: "ZlibError"
Expand Down Expand Up @@ -695,7 +716,7 @@ function providerMeta(metadata: Record<string, any> | undefined) {
export const toModelMessagesEffect = Effect.fnUntraced(function* (
input: WithParts[],
model: Provider.Model,
options?: { stripMedia?: boolean; toolOutputMaxChars?: number },
options?: { stripMedia?: boolean; toolOutputMaxChars?: number; toolInputMaxChars?: number },
) {
const result: UIMessage[] = []
const toolNames = new Set<string>()
Expand Down Expand Up @@ -866,7 +887,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
type: ("tool-" + part.tool) as `tool-${string}`,
state: "output-available",
toolCallId: part.callID,
input: part.state.input,
input: truncateToolInput(part.state.input, options?.toolInputMaxChars),
output,
...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}),
...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }),
Expand All @@ -887,7 +908,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
type: ("tool-" + part.tool) as `tool-${string}`,
state: "output-available",
toolCallId: part.callID,
input: part.state.input,
input: truncateToolInput(part.state.input, options?.toolInputMaxChars),
output,
...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}),
...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }),
Expand All @@ -897,7 +918,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
type: ("tool-" + part.tool) as `tool-${string}`,
state: "output-error",
toolCallId: part.callID,
input: part.state.input,
input: truncateToolInput(part.state.input, options?.toolInputMaxChars),
errorText: formatToolFailureForModel(part.state.error, part.state.metadata?.diagnostics?.failure),
...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}),
...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }),
Expand All @@ -911,7 +932,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
type: ("tool-" + part.tool) as `tool-${string}`,
state: "output-error",
toolCallId: part.callID,
input: part.state.input,
input: truncateToolInput(part.state.input, options?.toolInputMaxChars),
errorText: "[Tool execution was interrupted]",
...(part.metadata?.providerExecuted ? { providerExecuted: true } : {}),
...(differentModel ? {} : { callProviderMetadata: providerMeta(part.metadata) }),
Expand Down Expand Up @@ -976,7 +997,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
export function toModelMessages(
input: WithParts[],
model: Provider.Model,
options?: { stripMedia?: boolean; toolOutputMaxChars?: number },
options?: { stripMedia?: boolean; toolOutputMaxChars?: number; toolInputMaxChars?: number },
): Promise<ModelMessage[]> {
return Effect.runPromise(toModelMessagesEffect(input, model, options).pipe(Effect.provide(EffectLogger.layer)))
}
Expand Down
32 changes: 31 additions & 1 deletion packages/opencode/test/session/compaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,34 @@ describe("session.compaction.process", () => {
fn: async () => {
const session = await svc.create()
const first = await user(session.id, "first request")
await assistant(session.id, first.id, tmp.path)
const firstAssistant = await assistant(session.id, first.id, tmp.path)
const longQuestion = `${"Tauri backend Rust, OpenCode server TypeScript. ".repeat(200)}UNIQUE_COMPACTION_INPUT_TAIL`
await svc.updatePart({
id: PartID.ascending(),
messageID: firstAssistant.id,
sessionID: session.id,
type: "tool",
callID: "call-question",
tool: "question",
state: {
status: "error",
input: {
questions: [
{
question: longQuestion,
header: "Runtime",
options: [
{ label: "External", description: "Run Node separately" },
{ label: "Rust", description: "Rewrite backend" },
],
},
],
},
error: "invalid question",
time: { start: 0, end: 1 },
metadata: {},
},
})
const second = await user(session.id, "second request")
await assistant(session.id, second.id, tmp.path)
const compact = await user(session.id, "compact now")
Expand Down Expand Up @@ -948,6 +975,9 @@ describe("session.compaction.process", () => {
expect(compactPart?.tail_start_id).toBe(second.id)
expect(inputText(captured?.messages)).toContain("first request")
expect(inputText(captured?.messages)).not.toContain("second request")
const capturedPayload = JSON.stringify(captured?.messages)
expect(capturedPayload).toContain("Tool input truncated")
expect(capturedPayload).not.toContain("UNIQUE_COMPACTION_INPUT_TAIL")
},
})
})
Expand Down
63 changes: 63 additions & 0 deletions packages/opencode/test/session/message-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,69 @@ describe("session.message-v2.toModelMessage", () => {
])
})

test("bounds long tool inputs separately from tool output for compaction replay", async () => {
const userID = "m-user"
const assistantID = "m-assistant"
const longQuestion = `${"Tauri backend Rust, OpenCode server TypeScript. ".repeat(200)}UNIQUE_LONG_QUESTION_TAIL`
const error =
'The question tool was called with invalid arguments: SchemaError(Missing key at ["questions"][0]["options"][3]["description"]).\nPlease rewrite the input so it satisfies the expected schema.'
const input: MessageV2.WithParts[] = [
{
info: userInfo(userID),
parts: [
{
...basePart(userID, "u1"),
type: "text",
text: "ask a question",
},
] as MessageV2.Part[],
},
{
info: assistantInfo(assistantID, userID),
parts: [
{
...basePart(assistantID, "a1"),
type: "tool",
callID: "call-question",
tool: "question",
state: {
status: "error",
input: {
questions: [
{
question: longQuestion,
header: "Runtime",
options: [
{ label: "External", description: "Run Node separately" },
{ label: "Rust", description: "Rewrite backend" },
{ label: "Shell", description: "Spawn child process" },
{ label: "Unsure" },
],
},
],
},
error,
time: { start: 0, end: 1 },
metadata: {},
},
},
] as MessageV2.Part[],
},
]

const [, assistant, tool] = await MessageV2.toModelMessages(input, model, {
toolInputMaxChars: 200,
toolOutputMaxChars: 32,
})
const toolCall = assistant?.content[0] as any
const toolResult = tool?.content[0] as any

expect(toolCall.input.questions[0].question.length).toBeLessThanOrEqual(200)
expect(toolCall.input.questions[0].question).not.toContain("UNIQUE_LONG_QUESTION_TAIL")
expect(toolCall.input.questions[0].question).toContain("Tool input truncated")
expect(toolResult.output.value).toContain("SchemaError")
})

test("converts permission denial diagnostic into model-facing error text", async () => {
const userID = "m-user"
const assistantID = "m-assistant"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ function tool(
metadata: Record<string, unknown> = {},
input: Record<string, unknown> = {},
title = "",
error = "boom",
): ToolPart {
const state: ToolState =
status === "error"
? { status, input, error: "boom", time: { start: 0, end: 1 } }
? { status, input, error, time: { start: 0, end: 1 } }
: { status, input, output: "", title, metadata, time: { start: 0, end: 1 } }

return {
Expand Down Expand Up @@ -134,4 +135,58 @@ describe("contextTrowSummaryText", () => {

expect(contextToolSummaryText(part, i18n("en"))).toBe("Edit files 1 file")
})

test("keeps failed question summaries bounded instead of exposing raw schema errors", () => {
const schemaError =
'The question tool was called with invalid arguments: SchemaError(Missing key at ["questions"][0]["options"][3]["description"]).\nPlease rewrite the input so it satisfies the expected schema.'
const part = tool(
"question",
"question",
"error",
{},
{
questions: [
{
question: "Tauri backend Rust, OpenCode server TypeScript. ".repeat(20),
options: [
{ label: "External", description: "Run Node separately" },
{ label: "Rust", description: "Rewrite backend" },
{ label: "Shell", description: "Spawn child process" },
{ label: "Unsure" },
],
},
],
},
"",
schemaError,
)

const summary = contextToolSummaryText(part, i18n("en"))

expect(summary).toBe("Questions 1 question")
expect(summary).not.toContain("SchemaError")
expect(summary).not.toContain("\n")
expect(summary.length).toBeLessThanOrEqual(80)
})

test("summarizes todowrite input by item count instead of raw content", () => {
const part = tool(
"todos",
"todowrite",
"completed",
{},
{
todos: [
{ content: "Investigate tool input projection boundaries", status: "completed" },
{ content: "Add regression tests for compaction replay", status: "pending" },
],
},
)

const summary = contextToolSummaryText(part, i18n("en"))

expect(summary).toBe("To-dos 2 todos")
expect(summary).not.toContain("Investigate tool input projection boundaries")
expect(summary.length).toBeLessThanOrEqual(80)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { toolInfoForInput } from "../tool-info"
export function contextToolDetail(part: ToolPart, i18n: UiI18n): string | undefined {
const info = toolInfoForInput(part.tool, part.state.input ?? {}, toolStateMetadata(part.state), i18n)
if (info.subtitle) return info.subtitle
if (part.state.status === "error") return toolStateError(part.state)
if (part.state.status === "error") return undefined
if ((part.state.status === "running" || part.state.status === "completed") && part.state.title)
return part.state.title
const description = part.state.input?.description
Expand Down
12 changes: 10 additions & 2 deletions packages/ui/src/components/tool-info.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import type { ToolPart } from "@opencode-ai/sdk/v2"
import { getFilename } from "@opencode-ai/core/util/path"
import type { UiI18n } from "../context/i18n"
Expand Down Expand Up @@ -219,16 +219,24 @@
: undefined,
}
}
case TOOL_TODOWRITE:
case TOOL_TODOWRITE: {
const todoCount = Array.isArray(input.todos) ? input.todos.length : 0
return {
icon,
title: i18n.t("ui.tool.todos"),
subtitle: todoCount ? `${todoCount} ${todoCount === 1 ? "todo" : "todos"}` : undefined,
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
}
case TOOL_QUESTION:
}
case TOOL_QUESTION: {
const count = Array.isArray(input.questions) ? input.questions.length : 0
return {
icon,
title: i18n.t("ui.tool.questions"),
subtitle: count
? `${count} ${i18n.t(count > 1 ? "ui.common.question.other" : "ui.common.question.one")}`
: undefined,
}
}
case "skill":
return {
icon,
Expand Down
Loading