2026-02-08 16:25:25 +09:00
|
|
|
import type { Message, Part } from "@opencode-ai/sdk"
|
|
|
|
|
|
2026-04-28 14:51:38 -04:00
|
|
|
import { log } from "../shared/logger"
|
2026-02-08 16:25:25 +09:00
|
|
|
import type { CreatedHooks } from "../create-hooks"
|
|
|
|
|
|
|
|
|
|
type MessageWithParts = {
|
|
|
|
|
info: Message
|
|
|
|
|
parts: Part[]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type MessagesTransformOutput = { messages: MessageWithParts[] }
|
|
|
|
|
|
2026-04-28 14:51:38 -04:00
|
|
|
async function runMessagesTransformHookSafely<I, O>(
|
|
|
|
|
hookName: string,
|
|
|
|
|
handler: ((input: I, output: O) => unknown | Promise<unknown>) | null | undefined,
|
|
|
|
|
input: I,
|
|
|
|
|
output: O,
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
if (!handler) return
|
|
|
|
|
try {
|
|
|
|
|
await Promise.resolve(handler(input, output))
|
|
|
|
|
} catch (error) {
|
|
|
|
|
// Isolate per-handler failures so later handlers (notably toolPairValidator)
|
|
|
|
|
// always run. A throw here used to leave orphaned tool_use blocks in the
|
|
|
|
|
// post-compaction payload, producing API 400s like
|
|
|
|
|
// "tool_use ids were found without tool_result blocks immediately after".
|
|
|
|
|
log("[messages-transform] hook execution failed", {
|
|
|
|
|
hook: hookName,
|
|
|
|
|
error,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-08 16:25:25 +09:00
|
|
|
export function createMessagesTransformHandler(args: {
|
|
|
|
|
hooks: CreatedHooks
|
|
|
|
|
}): (input: Record<string, never>, output: MessagesTransformOutput) => Promise<void> {
|
|
|
|
|
return async (input, output): Promise<void> => {
|
2026-04-28 14:51:38 -04:00
|
|
|
await runMessagesTransformHookSafely(
|
|
|
|
|
"contextInjectorMessagesTransform",
|
|
|
|
|
args.hooks.contextInjectorMessagesTransform?.[
|
|
|
|
|
"experimental.chat.messages.transform"
|
|
|
|
|
],
|
|
|
|
|
input,
|
|
|
|
|
output,
|
|
|
|
|
)
|
2026-02-08 16:25:25 +09:00
|
|
|
|
2026-04-28 14:51:38 -04:00
|
|
|
await runMessagesTransformHookSafely(
|
|
|
|
|
"thinkingBlockValidator",
|
|
|
|
|
args.hooks.thinkingBlockValidator?.[
|
|
|
|
|
"experimental.chat.messages.transform"
|
|
|
|
|
],
|
|
|
|
|
input,
|
|
|
|
|
output,
|
|
|
|
|
)
|
2026-04-02 13:31:48 +09:00
|
|
|
|
2026-04-28 14:51:38 -04:00
|
|
|
await runMessagesTransformHookSafely(
|
|
|
|
|
"toolPairValidator",
|
|
|
|
|
args.hooks.toolPairValidator?.[
|
|
|
|
|
"experimental.chat.messages.transform"
|
|
|
|
|
],
|
|
|
|
|
input,
|
|
|
|
|
output,
|
|
|
|
|
)
|
2026-02-08 16:25:25 +09:00
|
|
|
}
|
|
|
|
|
}
|