openclaw/src/agents/pi-tools.ts

124 lines
3.8 KiB
TypeScript
Raw Normal View History

2025-12-17 20:38:52 +01:00
import type { AgentTool, AgentToolResult } from "@mariozechner/pi-ai";
2025-12-17 15:29:00 +00:00
import { codingTools, readTool } from "@mariozechner/pi-coding-agent";
import type { TSchema } from "@sinclair/typebox";
2025-12-17 15:29:00 +00:00
import { detectMime } from "../media/mime.js";
// TODO(steipete): Remove this wrapper once pi-mono ships file-magic MIME detection
// for `read` image payloads in `@mariozechner/pi-coding-agent` (then switch back to `codingTools` directly).
2025-12-17 20:38:52 +01:00
type ToolContentBlock = AgentToolResult<unknown>["content"][number];
type ImageContentBlock = Extract<ToolContentBlock, { type: "image" }>;
type TextContentBlock = Extract<ToolContentBlock, { type: "text" }>;
2025-12-17 15:29:00 +00:00
function sniffMimeFromBase64(base64: string): string | undefined {
const trimmed = base64.trim();
if (!trimmed) return undefined;
const take = Math.min(256, trimmed.length);
const sliceLen = take - (take % 4);
if (sliceLen < 8) return undefined;
try {
const head = Buffer.from(trimmed.slice(0, sliceLen), "base64");
return detectMime({ buffer: head });
} catch {
return undefined;
}
}
function rewriteReadImageHeader(text: string, mimeType: string): string {
// pi-coding-agent uses: "Read image file [image/png]"
if (text.startsWith("Read image file [") && text.endsWith("]")) {
return `Read image file [${mimeType}]`;
}
return text;
}
function normalizeReadImageResult(
2025-12-17 20:38:52 +01:00
result: AgentToolResult<unknown>,
2025-12-17 15:29:00 +00:00
filePath: string,
2025-12-17 20:38:52 +01:00
): AgentToolResult<unknown> {
2025-12-17 15:29:00 +00:00
const content = Array.isArray(result.content) ? result.content : [];
const image = content.find(
(b): b is ImageContentBlock =>
!!b &&
typeof b === "object" &&
2025-12-17 20:38:52 +01:00
(b as { type?: unknown }).type === "image" &&
typeof (b as { data?: unknown }).data === "string" &&
typeof (b as { mimeType?: unknown }).mimeType === "string",
2025-12-17 15:29:00 +00:00
);
if (!image) return result;
if (!image.data.trim()) {
throw new Error(`read: image payload is empty (${filePath})`);
}
const sniffed = sniffMimeFromBase64(image.data);
if (!sniffed) return result;
if (!sniffed.startsWith("image/")) {
throw new Error(
`read: file looks like ${sniffed} but was treated as ${image.mimeType} (${filePath})`,
);
}
if (sniffed === image.mimeType) return result;
const nextContent = content.map((block) => {
if (
block &&
typeof block === "object" &&
2025-12-17 20:38:52 +01:00
(block as { type?: unknown }).type === "image"
2025-12-17 15:29:00 +00:00
) {
2025-12-17 20:38:52 +01:00
const b = block as ImageContentBlock & { mimeType: string };
return { ...b, mimeType: sniffed } satisfies ImageContentBlock;
2025-12-17 15:29:00 +00:00
}
if (
block &&
typeof block === "object" &&
2025-12-17 20:38:52 +01:00
(block as { type?: unknown }).type === "text" &&
typeof (block as { text?: unknown }).text === "string"
2025-12-17 15:29:00 +00:00
) {
2025-12-17 20:38:52 +01:00
const b = block as TextContentBlock & { text: string };
return {
...b,
text: rewriteReadImageHeader(b.text, sniffed),
} satisfies TextContentBlock;
2025-12-17 15:29:00 +00:00
}
return block;
});
return { ...result, content: nextContent };
}
type AnyAgentTool = AgentTool<TSchema, unknown>;
2025-12-17 20:38:52 +01:00
function createClawdisReadTool(base: AnyAgentTool): AnyAgentTool {
2025-12-17 15:29:00 +00:00
return {
...base,
execute: async (toolCallId, params, signal) => {
const result = (await base.execute(
toolCallId,
params,
signal,
)) as AgentToolResult<unknown>;
2025-12-17 15:29:00 +00:00
const record =
params && typeof params === "object"
? (params as Record<string, unknown>)
: undefined;
const filePath =
typeof record?.path === "string" ? String(record.path) : "<unknown>";
return normalizeReadImageResult(result, filePath);
},
};
}
2025-12-17 20:38:52 +01:00
export function createClawdisCodingTools(): AnyAgentTool[] {
return (codingTools as unknown as AnyAgentTool[]).map((tool) =>
tool.name === readTool.name
? createClawdisReadTool(tool)
: (tool as AnyAgentTool),
2025-12-17 15:29:00 +00:00
);
}