Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(cowork): deliver tool images to the model as image_url parts

Akarshan Biswas767af2fa0c9b
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
index 026c04de6..72e1f47f7 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
@@ -13,6 +13,7 @@ export {
MemoryCatalogEntry,
MonitorUpdate,
SkillMeta,
+ ToolImage,
ToolOutputChunk,
ToolResult,
ToolSchema,
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
index e5bd3a6e7..dd5db071b 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
@@ -4,12 +4,20 @@ export interface SkillMeta {
description: string
}
+/** An image a tool returned, as a `data:` URL plus its display name. */
+export interface ToolImage {
+ dataUrl: string
+ name: string
+}
+
/** Outcome of a built-in tool execution. */
export interface ToolResult {
content: string
/** Display-only diff for write/edit; never part of model context. */
diff: string | null
isError: boolean
+ /** Present when the tool returned images (`read` of an image, `screenshot`). */
+ images?: ToolImage[]
}
/**
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index e44331516..4749adc6e 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -40,7 +40,7 @@ use crate::permissions::ToolPermissions;
use crate::skills::{self, SkillMeta};
use crate::tools::gate::{self, Decision, PromptKind, SessionGrants};
use crate::tools::jail;
-use crate::tools::{handlers, lookup, schema, ToolContext};
+use crate::tools::{handlers, lookup, schema, ImageContentPart, ToolContext};
use crate::workspace;
#[derive(Debug, Clone, Serialize, thiserror::Error)]
@@ -70,6 +70,10 @@ pub struct ToolResult {
/// Display-only diff for `write`/`edit`; never part of model context.
pub diff: Option<String>,
pub is_error: bool,
+ /// Images the tool returned (`read` of an image, `screenshot`), for the
+ /// caller to put in front of a vision model.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub images: Vec<ImageContentPart>,
}
/// The permanent store root holding `memory/` and `skills/`.
@@ -822,13 +826,14 @@ async fn execute_tool_inner(
if let Some(sink) = sink {
ctx = ctx.with_output_sink(sink);
}
- let (content, diff, _images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;
+ let (content, diff, images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;
let is_error =
content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));
Ok(ToolResult {
content,
diff,
is_error,
+ images: images.unwrap_or_default(),
})
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index f21c0017c..4a1f23995 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -29,6 +29,7 @@ pub mod web;
/// file, and the agent loop threads into the tool-result message so a vision
/// model sees the image.
#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct ImageContentPart {
/// `data:image/png;base64,...` URL, ready to embed in an `image_url` part.
pub data_url: String,
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.ts
index 583653987..11cd38295 100644
--- a/web-app/src/lib/__tests__/agentTools.test.ts
+++ b/web-app/src/lib/__tests__/agentTools.test.ts
@@ -113,6 +113,25 @@ describe('agentTools', () => {
expect(result.diff).toBeUndefined()
})
+ it('passes returned images through, dropping an empty list', async () => {
+ const images = [{ dataUrl: 'data:image/png;base64,AA', name: 'a.html' }]
+ executeTool.mockResolvedValue({
+ content: 'Screenshot of a.html (1280x960)',
+ diff: null,
+ isError: false,
+ images,
+ })
+ const { executeAgentTool } = await import('../agentTools')
+ expect(
+ (await executeAgentTool('screenshot', { path: 'a.html' }, 'thread-1'))
+ .images
+ ).toEqual(images)
+ executeTool.mockResolvedValue({ content: 'x', diff: null, isError: false })
+ expect(
+ (await executeAgentTool('read', { path: 'a.txt' }, 'thread-1')).images
+ ).toBeUndefined()
+ })
+
it('offers bash when the sandbox can enforce', async () => {
toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])
const { getAgentToolSchemas } = await import('../agentTools')
diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.ts
index c76797f38..151dd370d 100644
--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts
+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts
@@ -134,6 +134,17 @@ describe('dispatchCoworkTool', () => {
expect(out.diff).toBe('- a\n+ b')
})
+ it('carries returned images beside the output', async () => {
+ const images = [{ dataUrl: 'data:image/png;base64,AA', name: 'a.html' }]
+ executeAgentTool.mockResolvedValue({
+ content: 'Screenshot of a.html (1280x960)',
+ images,
+ })
+ const out = await dispatchCoworkTool(call('screenshot'), ctx())
+ expect(out.output).toBe('Screenshot of a.html (1280x960)')
+ expect(out.images).toEqual(images)
+ })
+
// A rejection would abort the whole run; the model can usually recover if it
// is simply told what failed.
it('turns a tool error into a result instead of throwing', async () => {
diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.ts
index 18f36b6b8..65e270b96 100644
--- a/web-app/src/lib/__tests__/coworkRunner.test.ts
+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts
@@ -16,6 +16,7 @@ import {
type ToolOutcome,
} from '../coworkRunner'
import { MAX_SESSION_TOKENS } from '../coworkBudget'
+import { encodeToolImageSentinel } from '../tool-image-sentinel'
const streamOf = (chunks: UIMessageChunk[]): ReadableStream<UIMessageChunk> =>
new ReadableStream({
@@ -400,6 +401,68 @@ describe('diff sidecar', () => {
})
})
+describe('tool images', () => {
+ const png = 'data:image/png;base64,iVBORw0KGgo='
+ const step: StepResult = {
+ text: '',
+ reasoning: '',
+ toolCalls: [
+ {
+ toolCallId: 'c1',
+ toolName: 'screenshot',
+ input: { path: 'index.html' },
+ } as PendingToolCall,
+ ],
+ usage: null,
+ aborted: false,
+ }
+ const outcomes = new Map<string, ToolOutcome>([
+ [
+ 'c1',
+ {
+ output: 'Screenshot of index.html (1280x960)',
+ images: [{ dataUrl: png, name: 'index.html' }],
+ },
+ ],
+ ])
+
+ // The image rides in the tool part's output as a sentinel the request fetch
+ // decodes into `image_url` parts on the `role: tool` message, the shape the
+ // CLI loop sends for a `read` of an image.
+ it('appends the image sentinel to the model-facing tool output', () => {
+ const msg = assistantMessageFor('m0', step, outcomes)
+ const part = msg.parts[0] as { output: string }
+ expect(part.output).toBe(
+ `Screenshot of index.html (1280x960)${encodeToolImageSentinel(png)}`
+ )
+ })
+
+ it('keeps the image out of the persisted transcript row', () => {
+ const [row] = turnsFor(step, outcomes)
+ expect(row.result).toBe('Screenshot of index.html (1280x960)')
+ expect(JSON.stringify(row)).not.toContain('iVBOR')
+ })
+
+ it('is sent to the model on the next step inside the tool result', async () => {
+ const d = deps(
+ [toolStep('screenshot'), textStep('looks right')],
+ vi.fn(async (): Promise<ToolOutcome> => ({
+ output: 'Screenshot of a.txt (1280x960)',
+ images: [{ dataUrl: png, name: 'a.txt' }],
+ }))
+ )
+ await runTurn({
+ messages: [user('render it')],
+ deps: d,
+ signal: new AbortController().signal,
+ })
+ const sent = d.sendStep.mock.calls[1][0] as UIMessage[]
+ expect(sent.map((m) => m.role)).toEqual(['user', 'assistant'])
+ const tool = (sent[1].parts as any[]).find((p) => p.type === 'tool-screenshot')
+ expect(tool.output).toContain(encodeToolImageSentinel(png))
+ })
+})
+
describe('run handles', () => {
it('aborts the stream, tools, children and pending asks together', () => {
const h = __testing.createHandle('s1', 'r1')
diff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
index e3eb9d1db..37971b3e0 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
@@ -13,6 +13,7 @@ import {
stripUnsupportedImageParts,
unwrapRetryError,
} from '../custom-chat-transport'
+import { encodeToolImageSentinel } from '../tool-image-sentinel'
const userMsg = (id: string, text: string): UIMessage =>
({
@@ -639,6 +640,25 @@ describe('stripUnsupportedImageParts', () => {
expect(out[0].parts).toEqual([textPart])
})
+ // A tool image would otherwise reach a text-only model as an image_url part
+ // it rejects; the caption stays so the model knows a screenshot was taken.
+ it('strips tool image sentinels from tool outputs when model lacks vision', () => {
+ const png = 'data:image/png;base64,AAA'
+ const toolPart = {
+ type: 'tool-screenshot',
+ toolCallId: 'c1',
+ state: 'output-available',
+ input: {},
+ output: `Screenshot of a.html${encodeToolImageSentinel(png)}`,
+ } as unknown as UIMessage['parts'][number]
+ const input = [{ id: 'a1', role: 'assistant', parts: [toolPart] } as UIMessage]
+ const out = stripUnsupportedImageParts(input, false)
+ const output = (out[0].parts[0] as { output: string }).output
+ expect(output).not.toContain('AAA')
+ expect(output).toContain('Screenshot of a.html')
+ expect(stripUnsupportedImageParts(input, true)).toBe(input)
+ })
+
it('drops AI-SDK image-type parts when model lacks vision', () => {
const imagePartV2 = {
type: 'image',
diff --git a/web-app/src/lib/__tests__/tool-image-sentinel.test.ts b/web-app/src/lib/__tests__/tool-image-sentinel.test.ts
new file mode 100644
index 000000000..adb330282
--- /dev/null
+++ b/web-app/src/lib/__tests__/tool-image-sentinel.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest'
+import {
+ encodeToolImageSentinel,
+ hasToolImageSentinel,
+ splitToolImageSentinels,
+ stripToolImageSentinels,
+} from '../tool-image-sentinel'
+import { decodeToolImageSentinelsInBody } from '../model-factory'
+
+const png = 'data:image/png;base64,iVBORw0KGgo='
+
+describe('tool-image-sentinel', () => {
+ it('round-trips a sentinel back to an image_url part', () => {
+ const encoded = encodeToolImageSentinel(png)
+ expect(hasToolImageSentinel(encoded)).toBe(true)
+ expect(splitToolImageSentinels(encoded)).toEqual([
+ { type: 'image_url', image_url: { url: png, detail: 'auto' } },
+ ])
+ })
+
+ it('keeps surrounding text in order', () => {
+ const text = `Screenshot of a.html${encodeToolImageSentinel(png)}tail`
+ expect(splitToolImageSentinels(text)).toEqual([
+ { type: 'text', text: 'Screenshot of a.html' },
+ { type: 'image_url', image_url: { url: png, detail: 'auto' } },
+ { type: 'text', text: 'tail' },
+ ])
+ })
+
+ it('returns null for plain text', () => {
+ expect(splitToolImageSentinels('no image here')).toBeNull()
+ })
+
+ it('strips sentinels for a model without vision', () => {
+ const text = `Screenshot of a.html${encodeToolImageSentinel(png)}`
+ expect(stripToolImageSentinels(text, ' (image omitted)')).toBe(
+ 'Screenshot of a.html (image omitted)'
+ )
+ expect(stripToolImageSentinels('plain', 'x')).toBe('plain')
+ })
+})
+
+describe('decodeToolImageSentinelsInBody', () => {
+ // Mirrors what `loop.rs` sends on the CLI: a tool message whose content is
+ // a text part followed by image_url parts.
+ it('turns a sentinel-bearing tool message into content parts', () => {
+ const body = {
+ messages: [
+ { role: 'user', content: 'render it' },
+ {
+ role: 'tool',
+ tool_call_id: 'c1',
+ content: `Screenshot of a.html (1280x960)${encodeToolImageSentinel(png)}`,
+ },
+ ],
+ }
+ decodeToolImageSentinelsInBody(body)
+ expect(body.messages[1].content).toEqual([
+ { type: 'text', text: 'Screenshot of a.html (1280x960)' },
+ { type: 'image_url', image_url: { url: png, detail: 'auto' } },
+ ])
+ expect(body.messages[0].content).toBe('render it')
+ })
+
+ it('leaves non-tool roles and plain tool messages alone', () => {
+ const user = `user typed${encodeToolImageSentinel(png)}`
+ const body = {
+ messages: [
+ { role: 'user', content: user },
+ { role: 'tool', tool_call_id: 'c1', content: 'plain result' },
+ ],
+ }
+ decodeToolImageSentinelsInBody(body)
+ expect(body.messages[0].content).toBe(user)
+ expect(body.messages[1].content).toBe('plain result')
+ })
+})
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index b02475824..f4412031c 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -16,6 +16,7 @@ import {
type MemoryCatalogEntry,
type MonitorUpdate,
type SandboxStatus,
+ type ToolImage,
type ToolSchema,
type WorkspaceScope,
} from '@janhq/tauri-plugin-agent-tools-api'
@@ -124,7 +125,7 @@ export async function getAgentToolSchemas(): Promise<ToolSchema[]> {
return schemaCache
}
-export type { MemoryCatalogEntry }
+export type { MemoryCatalogEntry, ToolImage }
/**
* Injection caps for the shared memory store. The *store* is unbounded; what
@@ -217,6 +218,8 @@ type AgentToolResult = {
error?: string
/** Unified diff from `write`/`edit`. Display-only; never sent to the model. */
diff?: string
+ /** Images the tool returned, for a vision model to see. */
+ images?: ToolImage[]
}
const messageOf = (e: unknown): string =>
@@ -282,7 +285,11 @@ export async function executeAgentTool(
// The store changed, so the recall injections must not keep serving the
// snapshot taken before this note existed.
if (toolName === 'memory_write') invalidateMemory()
- return { content: result.content, diff: result.diff ?? undefined }
+ return {
+ content: result.content,
+ diff: result.diff ?? undefined,
+ images: result.images?.length ? result.images : undefined,
+ }
} catch (e) {
return { error: messageOf(e) }
}
diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.ts
index 0db501082..ee2047632 100644
--- a/web-app/src/lib/coworkDispatch.ts
+++ b/web-app/src/lib/coworkDispatch.ts
@@ -162,6 +162,7 @@ export async function dispatchCoworkTool(
? result.content
: JSON.stringify(result.content ?? ''),
diff: result.diff,
+ images: result.images,
}
} catch (e) {
return {
diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.ts
index c4f521e62..9937dc197 100644
--- a/web-app/src/lib/coworkRunner.ts
+++ b/web-app/src/lib/coworkRunner.ts
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { UIMessage, UIMessageChunk } from 'ai'
import type { AskAnswer, CoworkTurn, Usage } from '@/types/coworkSession'
+import type { ToolImage } from '@/lib/agentTools'
import {
MAX_AGENT_STEPS,
budgetExceeded,
@@ -9,6 +10,7 @@ import {
type BudgetStop,
} from '@/lib/coworkBudget'
import { attachPings } from '@/lib/coworkPing'
+import { encodeToolImageSentinel } from '@/lib/tool-image-sentinel'
/**
* The Cowork agent loop.
@@ -36,6 +38,11 @@ export type ToolOutcome = {
isError?: boolean
/** Display-only unified diff. Never reaches the model. */
diff?: string
+ /** Images the tool returned (`read` of an image, `screenshot`). They reach
+ * the model inside the tool result, as `image_url` parts on the `role: tool`
+ * message (see `tool-image-sentinel.ts`), and are never persisted: a
+ * screenshot is megabytes of base64 and the session store is `settings.json`. */
+ images?: ToolImage[]
}
/** One model turn's worth of stream, folded into a shape the loop can act on. */
@@ -261,6 +268,13 @@ export async function consumeStep(
return result
}
+/** The model-facing tail of a tool output: one sentinel per returned image. */
+function toolImageSentinels(outcome: ToolOutcome): string {
+ return (outcome.images ?? [])
+ .map((img) => encodeToolImageSentinel(img.dataUrl))
+ .join('')
+}
+
/** Assemble the assistant message for a completed step, results included. */
export function assistantMessageFor(
id: string,
@@ -286,7 +300,7 @@ export function assistantMessageFor(
}
if (outcome) {
if (outcome.isError) part.errorText = outcome.output
- else part.output = outcome.output
+ else part.output = outcome.output + toolImageSentinels(outcome)
}
parts.push(part)
}
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index bb0cf03eb..59fa93f46 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -12,6 +12,10 @@ import {
InvalidToolInputError,
} from 'ai'
import { repairToolArgs } from './toolCallRepair'
+import {
+ hasToolImageSentinel,
+ stripToolImageSentinels,
+} from './tool-image-sentinel'
import { useServiceStore } from '@/hooks/useServiceHub'
import { useToolAvailable } from '@/hooks/useToolAvailable'
import { ModelFactory } from './model-factory'
@@ -493,26 +497,42 @@ export function stripUnsupportedImageParts(
return message
}
let touched = false
- const nextParts = message.parts.filter((part) => {
- const type = (part as { type?: string }).type
- if (type === 'image') {
- touched = true
- return false
- }
- if (type === 'file') {
- const mediaType = (part as { mediaType?: string }).mediaType
- if (typeof mediaType === 'string' && mediaType.startsWith('image/')) {
+ const nextParts = message.parts
+ .filter((part) => {
+ const type = (part as { type?: string }).type
+ if (type === 'image') {
touched = true
return false
}
- }
- return true
- })
+ if (type === 'file') {
+ const mediaType = (part as { mediaType?: string }).mediaType
+ if (typeof mediaType === 'string' && mediaType.startsWith('image/')) {
+ touched = true
+ return false
+ }
+ }
+ return true
+ })
+ .map((part) => {
+ // A tool image (see tool-image-sentinel.ts) would decode into an
+ // image_url part on the tool message; a text-only model rejects that.
+ const output = (part as { output?: unknown }).output
+ if (typeof output !== 'string' || !hasToolImageSentinel(output)) {
+ return part
+ }
+ touched = true
+ return {
+ ...part,
+ output: stripToolImageSentinels(output, TOOL_IMAGE_OMITTED),
+ } as typeof part
+ })
if (!touched) return message
return { ...message, parts: nextParts } as UIMessage
})
}
+const TOOL_IMAGE_OMITTED = ' (image omitted: the model has no vision)'
+
const RESOLVED_TOOL_STATES = new Set([
'output-available',
'output-error',
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 24399c61b..bfcf12004 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -62,6 +62,10 @@ import { SessionInfo } from '@janhq/core'
import { fetch as httpFetch } from '@tauri-apps/plugin-http'
import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'
import { hasVideoSentinel, splitVideoSentinels } from './video-sentinel'
+import {
+ hasToolImageSentinel,
+ splitToolImageSentinels,
+} from './tool-image-sentinel'
import { filterDefaultSseEvents } from './sseEventTypeFilter'
import { isPlatformTauri } from '@/lib/platform/utils'
import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'
@@ -471,6 +475,7 @@ export function createCustomFetch(
if (!includeOurParams) {
decodeAudioSentinelsInBody(rawBody)
decodeVideoSentinelsInBody(rawBody)
+ decodeToolImageSentinelsInBody(rawBody)
return rawBody
}
const normalised: Record<string, unknown> = {}
@@ -507,6 +512,7 @@ export function createCustomFetch(
}
decodeAudioSentinelsInBody(merged)
decodeVideoSentinelsInBody(merged)
+ decodeToolImageSentinelsInBody(merged)
return merged
}
@@ -798,6 +804,25 @@ export function decodeVideoSentinelsInBody(body: Record<string, unknown>): void
}
}
+// Rewrites a sentinel-bearing `role: tool` message (planted by Cowork's
+// `assistantMessageFor` for a tool that returned images) into a text part plus
+// OpenAI `image_url` parts, the shape the CLI loop sends for a `read` of an
+// image. Mutates `body.messages` in place.
+export function decodeToolImageSentinelsInBody(
+ body: Record<string, unknown>
+): void {
+ const messages = body.messages
+ if (!Array.isArray(messages)) return
+ for (const msg of messages) {
+ if (!msg || typeof msg !== 'object') continue
+ const m = msg as { role?: string; content?: unknown }
+ if (m.role !== 'tool' || typeof m.content !== 'string') continue
+ if (!hasToolImageSentinel(m.content)) continue
+ const split = splitToolImageSentinels(m.content)
+ if (split) m.content = split
+ }
+}
+
type ApiKeyHeaderMode =
| 'authorization-bearer'
| 'x-api-key'
diff --git a/web-app/src/lib/tool-image-sentinel.ts b/web-app/src/lib/tool-image-sentinel.ts
new file mode 100644
index 000000000..9c86c4940
--- /dev/null
+++ b/web-app/src/lib/tool-image-sentinel.ts
@@ -0,0 +1,65 @@
+// A tool result carrying an image (`read` of an image file, `screenshot`) goes
+// to the model as a `role: tool` message whose content is an array of a text
+// part plus OpenAI `image_url` parts, the shape the CLI loop sends. The AI SDK
+// cannot produce that: `@ai-sdk/openai-compatible` stringifies every
+// structured tool output. So, as with audio and video attachments, the image
+// rides inside the tool part's output text as a sentinel and the request fetch
+// decodes it back into content parts.
+
+const PREFIX = ' __JAN_TOOL_IMAGE__'
+const SUFFIX = ' '
+
+const SENTINEL_REGEX =
+ / __JAN_TOOL_IMAGE__(data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+) /g
+
+export function encodeToolImageSentinel(dataUrl: string): string {
+ return `${PREFIX}${dataUrl}${SUFFIX}`
+}
+
+export function hasToolImageSentinel(text: string): boolean {
+ return text.includes(PREFIX)
+}
+
+export type ImageUrlPart = {
+ type: 'image_url'
+ image_url: { url: string; detail: 'auto' }
+}
+
+/**
+ * Splits a sentinel-bearing string into ordered OpenAI content parts. Returns
+ * null when no sentinel is present so callers keep the string form.
+ */
+export function splitToolImageSentinels(
+ text: string
+): Array<{ type: 'text'; text: string } | ImageUrlPart> | null {
+ if (!hasToolImageSentinel(text)) return null
+ const parts: Array<{ type: 'text'; text: string } | ImageUrlPart> = []
+ let lastIndex = 0
+ SENTINEL_REGEX.lastIndex = 0
+ for (
+ let m = SENTINEL_REGEX.exec(text);
+ m !== null;
+ m = SENTINEL_REGEX.exec(text)
+ ) {
+ const [match, url] = m
+ if (m.index > lastIndex) {
+ parts.push({ type: 'text', text: text.slice(lastIndex, m.index) })
+ }
+ parts.push({ type: 'image_url', image_url: { url, detail: 'auto' } })
+ lastIndex = m.index + match.length
+ }
+ if (lastIndex < text.length) {
+ parts.push({ type: 'text', text: text.slice(lastIndex) })
+ }
+ return parts
+}
+
+/** Removes every sentinel, leaving `replacement` in its place. */
+export function stripToolImageSentinels(
+ text: string,
+ replacement: string
+): string {
+ if (!hasToolImageSentinel(text)) return text
+ SENTINEL_REGEX.lastIndex = 0
+ return text.replace(SENTINEL_REGEX, replacement)
+}