Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

fix(agent): route Inkling's tool-result images through a follow-up user message

Matt Kissinger6f2a6a3bc749
diff --git a/src/agent/providers.ts b/src/agent/providers.ts
index 49733ecb..3bc5be00 100644
--- a/src/agent/providers.ts
+++ b/src/agent/providers.ts
@@ -20,6 +20,7 @@ import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import type { LanguageModelV3 } from '@ai-sdk/provider';
import { ensureStreamStart } from './stream-start';
+import { splitToolResultImages } from './split-tool-result-images';
/** OpenRouter's unified reasoning control (@openrouter/ai-sdk-provider chat setting):
* an effort keyword or a hard reasoning-token budget. Passed straight through to
@@ -100,6 +101,12 @@ export interface OpenRouterModelOptions {
maxTokens?: number;
/** Unified reasoning control (effort keyword or token budget). */
reasoning?: OpenRouterReasoning;
+ /** Move tool-result images to a follow-up user message instead of leaving
+ * them inline (see split-tool-result-images.ts). Together's hosting of
+ * Thinking Machines' Inkling rejects images embedded in a `tool` message
+ * outright; other OpenRouter models don't need this. Model-scoped by the
+ * caller (see the 'openrouter' case below), default false. */
+ splitToolResultImages?: boolean;
}
/**
@@ -108,12 +115,13 @@ export interface OpenRouterModelOptions {
*/
export function makeOpenRouterModel(opts: OpenRouterModelOptions): Model {
const openrouter = createOpenRouter({ apiKey: opts.apiKey ?? process.env['OPENROUTER_API_KEY'] });
- const provider = ensureStreamStart(
+ let provider = ensureStreamStart(
openrouter.chat(
opts.modelId,
opts.reasoning ? { reasoning: opts.reasoning } : {},
) as LanguageModelV3,
);
+ if (opts.splitToolResultImages) provider = splitToolResultImages(provider);
return new VercelModel({
provider,
...(opts.maxTokens != null ? { maxTokens: opts.maxTokens } : {}),
@@ -338,6 +346,9 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
...(maxTokens != null ? { maxTokens } : {}),
...(reasoning ? { reasoning } : {}),
+ // Together's Inkling hosting rejects images embedded in a tool-result
+ // message (verified live 2026-07-19) — see split-tool-result-images.ts.
+ ...(desc.model === 'thinkingmachines/inkling' ? { splitToolResultImages: true } : {}),
});
}
default: {
diff --git a/src/agent/split-tool-result-images.test.ts b/src/agent/split-tool-result-images.test.ts
new file mode 100644
index 00000000..dba81fef
--- /dev/null
+++ b/src/agent/split-tool-result-images.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Regression tests for `splitToolResultImages` — the Together/Inkling fix.
+ *
+ * Build a fake LanguageModelV3 whose doStream just captures the options it
+ * received, so we can assert on the REWRITTEN prompt shape. No network.
+ */
+import { test, expect } from 'bun:test';
+import { splitToolResultImages } from './split-tool-result-images';
+
+function fakeModel(captured: { options?: unknown }) {
+ return {
+ specificationVersion: 'v3',
+ provider: 'fake',
+ modelId: 'fake/m',
+ doStream: async (opts: unknown) => {
+ captured.options = opts;
+ return {
+ stream: new ReadableStream({
+ start(ctrl) {
+ ctrl.close();
+ },
+ }),
+ };
+ },
+ } as never;
+}
+
+test('moves a file-data tool-result image into a follow-up user message', async () => {
+ const captured: { options?: unknown } = {};
+ const wrapped = splitToolResultImages(fakeModel(captured));
+ await (wrapped as unknown as { doStream: (o: unknown) => Promise<unknown> }).doStream({
+ prompt: [
+ { role: 'user', content: [{ type: 'text', text: 'render it' }] },
+ {
+ role: 'tool',
+ content: [
+ {
+ type: 'tool-result',
+ toolCallId: 'call_1',
+ toolName: 'kiln_render',
+ output: {
+ type: 'content',
+ value: [
+ { type: 'text', text: 'rendered ok' },
+ { type: 'file-data', data: 'BASE64BYTES', mediaType: 'image/png' },
+ ],
+ },
+ },
+ ],
+ },
+ ],
+ });
+ const prompt = (captured.options as { prompt: unknown[] }).prompt;
+ expect(prompt).toHaveLength(3);
+ const toolMessage = prompt[1] as {
+ role: string;
+ content: Array<{ output: { value: unknown[] } }>;
+ };
+ expect(toolMessage.role).toBe('tool');
+ expect(toolMessage.content[0]!.output.value).toEqual([{ type: 'text', text: 'rendered ok' }]);
+ expect(prompt[2]).toEqual({
+ role: 'user',
+ content: [{ type: 'file', data: 'BASE64BYTES', mediaType: 'image/png' }],
+ });
+});
+
+test('is a no-op for a tool result with no image', async () => {
+ const captured: { options?: unknown } = {};
+ const wrapped = splitToolResultImages(fakeModel(captured));
+ const original = {
+ prompt: [
+ {
+ role: 'tool',
+ content: [
+ {
+ type: 'tool-result',
+ toolCallId: 'call_1',
+ toolName: 'kiln_validate',
+ output: { type: 'text', value: 'ok' },
+ },
+ ],
+ },
+ ],
+ };
+ await (wrapped as unknown as { doStream: (o: unknown) => Promise<unknown> }).doStream(original);
+ expect((captured.options as { prompt: unknown[] }).prompt).toEqual(original.prompt);
+});
+
+test('passes through non-doStream properties', () => {
+ const wrapped = splitToolResultImages(fakeModel({}));
+ expect((wrapped as unknown as { specificationVersion: string }).specificationVersion).toBe('v3');
+ expect((wrapped as unknown as { modelId: string }).modelId).toBe('fake/m');
+});
diff --git a/src/agent/split-tool-result-images.ts b/src/agent/split-tool-result-images.ts
new file mode 100644
index 00000000..10e7316c
--- /dev/null
+++ b/src/agent/split-tool-result-images.ts
@@ -0,0 +1,80 @@
+/**
+ * `splitToolResultImages` — move any image inside a tool-result message into
+ * a synthetic follow-up user message instead.
+ *
+ * WHY THIS EXISTS: Kiln's agent loop returns the kiln_render/kiln_screenshot
+ * image as part of the tool-result content (Strands' `formatToolResultOutput`
+ * emits a `file-data` part inside the `role: 'tool'` message). Most
+ * OpenRouter-hosted models accept that shape fine, but Together's hosting of
+ * Thinking Machines' Inkling model rejects it outright: "Multimodal
+ * processing failed: multimodal placeholder count mismatch... refusing to
+ * dispatch" — REGARDLESS of any inline placeholder text. Verified live
+ * against the API (2026-07-19): the identical image bytes succeed in a plain
+ * `user` message and fail inside a `tool` message whether or not a `<image>`
+ * placeholder is added — this is a structural "no images in tool messages"
+ * limitation on that endpoint, not a missing-token formatting issue.
+ *
+ * This proxy rewrites the outgoing prompt: any `file-data` part is stripped
+ * out of its tool-result message and re-appended as a same-turn synthetic
+ * `user` message carrying the same bytes as a standard `file` part. Verified
+ * against the live API in exactly this shape (tool-result-without-image
+ * immediately followed by a plain user message with the image) — HTTP 200.
+ *
+ * Model-scoped in providers.ts, NOT applied broadly — other OpenRouter
+ * models already work fine with images embedded in the tool-result shape and
+ * don't need (or want) this rewrite.
+ */
+import type {
+ LanguageModelV3,
+ LanguageModelV3CallOptions,
+ LanguageModelV3FilePart,
+ LanguageModelV3Message,
+ LanguageModelV3Prompt,
+} from '@ai-sdk/provider';
+
+function rewritePrompt(prompt: LanguageModelV3Prompt): LanguageModelV3Prompt {
+ const rewritten: LanguageModelV3Message[] = [];
+ for (const message of prompt) {
+ if (message.role !== 'tool') {
+ rewritten.push(message);
+ continue;
+ }
+ const images: LanguageModelV3FilePart[] = [];
+ const nextContent = message.content.map((part) => {
+ if (part.type !== 'tool-result' || part.output.type !== 'content') return part;
+ const keptValue = part.output.value.filter((v) => {
+ if (v.type !== 'file-data') return true;
+ images.push({
+ type: 'file',
+ data: v.data,
+ mediaType: v.mediaType,
+ ...(v.filename ? { filename: v.filename } : {}),
+ });
+ return false;
+ });
+ return { ...part, output: { ...part.output, value: keptValue } };
+ });
+ rewritten.push({ ...message, content: nextContent });
+ if (images.length > 0) rewritten.push({ role: 'user', content: images });
+ }
+ return rewritten;
+}
+
+/**
+ * Wrap a `LanguageModelV3` so tool-result images are moved to a follow-up
+ * `user` message before every call. All other properties/methods pass
+ * through unchanged.
+ */
+export function splitToolResultImages(model: LanguageModelV3): LanguageModelV3 {
+ const origDoStream = model.doStream.bind(model);
+ return new Proxy(model, {
+ get(target, prop, receiver) {
+ if (prop === 'doStream') {
+ return (options: LanguageModelV3CallOptions) =>
+ origDoStream({ ...options, prompt: rewritePrompt(options.prompt) });
+ }
+ const value = Reflect.get(target, prop, receiver);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}