|
| 1 | +import type { EndpointMessage } from "../../endpoints/endpoints"; |
| 2 | + |
| 3 | +export type FileRefPayload = { |
| 4 | + name: string; |
| 5 | + mime: string; |
| 6 | + base64: string; |
| 7 | +}; |
| 8 | + |
| 9 | +export type RefKind = { |
| 10 | + prefix: string; |
| 11 | + matches: (mime: string) => boolean; |
| 12 | + toDataUrl?: (payload: FileRefPayload) => string; |
| 13 | +}; |
| 14 | + |
| 15 | +export type ResolvedFileRef = FileRefPayload & { refKind: RefKind }; |
| 16 | +export type FileRefResolver = (ref: string) => ResolvedFileRef | undefined; |
| 17 | + |
| 18 | +const IMAGE_REF_KIND: RefKind = { |
| 19 | + prefix: "image", |
| 20 | + matches: (mime) => typeof mime === "string" && mime.startsWith("image/"), |
| 21 | + toDataUrl: (payload) => `data:${payload.mime};base64,${payload.base64}`, |
| 22 | +}; |
| 23 | + |
| 24 | +const DEFAULT_REF_KINDS: RefKind[] = [IMAGE_REF_KIND]; |
| 25 | + |
| 26 | +/** |
| 27 | + * Build a resolver that maps short ref strings (e.g. "image_1") to the |
| 28 | + * corresponding file payload for the latest user message containing files of |
| 29 | + * the allowed kinds. Currently only images are exposed to end users, but the |
| 30 | + * plumbing supports additional kinds later. |
| 31 | + */ |
| 32 | +export function buildFileRefResolver( |
| 33 | + messages: EndpointMessage[], |
| 34 | + refKinds: RefKind[] = DEFAULT_REF_KINDS |
| 35 | +): FileRefResolver | undefined { |
| 36 | + if (!Array.isArray(refKinds) || refKinds.length === 0) return undefined; |
| 37 | + |
| 38 | + // Find the newest user message that has at least one matching file |
| 39 | + let lastUserWithFiles: EndpointMessage | undefined; |
| 40 | + for (let i = messages.length - 1; i >= 0; i -= 1) { |
| 41 | + const msg = messages[i]; |
| 42 | + if (msg.from !== "user") continue; |
| 43 | + const hasMatch = (msg.files ?? []).some((file) => { |
| 44 | + const mime = file?.mime; |
| 45 | + return refKinds.some((kind) => kind.matches(mime ?? "")); |
| 46 | + }); |
| 47 | + if (hasMatch) { |
| 48 | + lastUserWithFiles = msg; |
| 49 | + break; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (!lastUserWithFiles) return undefined; |
| 54 | + |
| 55 | + // Bucket matched files by ref kind while preserving order within the message |
| 56 | + const buckets = new Map<RefKind, FileRefPayload[]>(); |
| 57 | + for (const file of lastUserWithFiles.files ?? []) { |
| 58 | + const mime = file?.mime ?? ""; |
| 59 | + const kind = refKinds.find((k) => k.matches(mime)); |
| 60 | + if (!kind) continue; |
| 61 | + const payload: FileRefPayload = { name: file.name, mime, base64: file.value }; |
| 62 | + const arr = buckets.get(kind) ?? []; |
| 63 | + arr.push(payload); |
| 64 | + buckets.set(kind, arr); |
| 65 | + } |
| 66 | + |
| 67 | + if (buckets.size === 0) return undefined; |
| 68 | + |
| 69 | + const resolver: FileRefResolver = (ref) => { |
| 70 | + if (!ref || typeof ref !== "string") return undefined; |
| 71 | + const trimmed = ref.trim().toLowerCase(); |
| 72 | + for (const kind of refKinds) { |
| 73 | + const match = new RegExp(`^${kind.prefix}_(\\d+)$`).exec(trimmed); |
| 74 | + if (!match) continue; |
| 75 | + const idx = Number(match[1]) - 1; |
| 76 | + const files = buckets.get(kind) ?? []; |
| 77 | + if (Number.isFinite(idx) && idx >= 0 && idx < files.length) { |
| 78 | + const payload = files[idx]; |
| 79 | + return payload ? { ...payload, refKind: kind } : undefined; |
| 80 | + } |
| 81 | + } |
| 82 | + return undefined; |
| 83 | + }; |
| 84 | + |
| 85 | + return resolver; |
| 86 | +} |
| 87 | + |
| 88 | +export function buildImageRefResolver(messages: EndpointMessage[]): FileRefResolver | undefined { |
| 89 | + return buildFileRefResolver(messages, [IMAGE_REF_KIND]); |
| 90 | +} |
| 91 | + |
| 92 | +type FieldRule = { |
| 93 | + keys: string[]; |
| 94 | + action: "attachPayload" | "replaceWithDataUrl"; |
| 95 | + attachKey?: string; |
| 96 | + allowedPrefixes?: string[]; // limit to specific ref kinds (e.g. ["image"]) |
| 97 | +}; |
| 98 | + |
| 99 | +const DEFAULT_FIELD_RULES: FieldRule[] = [ |
| 100 | + { |
| 101 | + keys: ["image_ref"], |
| 102 | + action: "attachPayload", |
| 103 | + attachKey: "image", |
| 104 | + allowedPrefixes: ["image"], |
| 105 | + }, |
| 106 | + { |
| 107 | + keys: ["input_image"], |
| 108 | + action: "replaceWithDataUrl", |
| 109 | + allowedPrefixes: ["image"], |
| 110 | + }, |
| 111 | +]; |
| 112 | + |
| 113 | +/** |
| 114 | + * Walk tool args and hydrate known ref fields while keeping logging lightweight. |
| 115 | + * Only image refs are recognized for now to preserve current behavior. |
| 116 | + */ |
| 117 | +export function attachFileRefsToArgs( |
| 118 | + argsObj: Record<string, unknown>, |
| 119 | + resolveRef?: FileRefResolver, |
| 120 | + fieldRules: FieldRule[] = DEFAULT_FIELD_RULES |
| 121 | +): void { |
| 122 | + if (!resolveRef) return; |
| 123 | + |
| 124 | + const visit = (node: unknown): void => { |
| 125 | + if (!node || typeof node !== "object") return; |
| 126 | + if (Array.isArray(node)) { |
| 127 | + for (const v of node) visit(v); |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + const obj = node as Record<string, unknown>; |
| 132 | + for (const [key, value] of Object.entries(obj)) { |
| 133 | + if (typeof value !== "string") { |
| 134 | + if (value && typeof value === "object") visit(value); |
| 135 | + continue; |
| 136 | + } |
| 137 | + |
| 138 | + const resolved = resolveRef(value); |
| 139 | + if (!resolved) continue; |
| 140 | + |
| 141 | + const rule = fieldRules.find((r) => r.keys.includes(key)); |
| 142 | + if (!rule) continue; |
| 143 | + if (rule.allowedPrefixes && !rule.allowedPrefixes.includes(resolved.refKind.prefix)) continue; |
| 144 | + |
| 145 | + if (rule.action === "attachPayload") { |
| 146 | + const targetKey = rule.attachKey ?? "file"; |
| 147 | + if ( |
| 148 | + typeof obj[targetKey] !== "object" || |
| 149 | + obj[targetKey] === null || |
| 150 | + Array.isArray(obj[targetKey]) |
| 151 | + ) { |
| 152 | + obj[targetKey] = { |
| 153 | + name: resolved.name, |
| 154 | + mime: resolved.mime, |
| 155 | + base64: resolved.base64, |
| 156 | + }; |
| 157 | + } |
| 158 | + } else if (rule.action === "replaceWithDataUrl") { |
| 159 | + const toUrl = |
| 160 | + resolved.refKind.toDataUrl ?? |
| 161 | + ((p: FileRefPayload) => `data:${p.mime};base64,${p.base64}`); |
| 162 | + obj[key] = toUrl(resolved); |
| 163 | + } |
| 164 | + } |
| 165 | + }; |
| 166 | + |
| 167 | + visit(argsObj); |
| 168 | +} |
0 commit comments