| 163 | |
| 164 | // 辅助函数:从字符串中提取以指定 key 开头的完整 JSON 对象(支持嵌套) |
| 165 | function extractJsonObject(str: string, key: string): string | null { |
| 166 | const idx = str.indexOf(`"${key}"`); |
| 167 | if (idx === -1) return null; |
| 168 | // 向前找到 { |
| 169 | let start = idx; |
| 170 | while (start > 0 && str[start] !== "{") start--; |
| 171 | if (str[start] !== "{") return null; |
| 172 | // 向后匹配括号 |
| 173 | let depth = 0; |
| 174 | let inString = false; |
| 175 | let escape = false; |
| 176 | for (let i = start; i < str.length; i++) { |
| 177 | const ch = str[i]; |
| 178 | if (escape) { escape = false; continue; } |
| 179 | if (ch === "\\") { escape = true; continue; } |
| 180 | if (ch === '"' && !escape) { inString = !inString; continue; } |
| 181 | if (inString) continue; |
| 182 | if (ch === "{") depth++; |
| 183 | else if (ch === "}") { depth--; if (depth === 0) return str.slice(start, i + 1); } |
| 184 | } |
| 185 | return null; |
| 186 | } |
| 187 | |
| 188 | function convertToolMessages(messages: any[]): any[] { |
| 189 | return messages.map((m: any) => { |