| 179 | } |
| 180 | |
| 181 | function getBestRetoolAccount(modelId: string) { |
| 182 | const now = Date.now(); |
| 183 | // find agentIds for this model |
| 184 | const record = AVAILABLE_MODELS.find((m) => m.id === modelId); |
| 185 | if (!record) return undefined; |
| 186 | const { agents: allowed } = record; |
| 187 | // filter accounts that have a valid agent match |
| 188 | const candidates = RETOOL_ACCOUNTS.filter((acc) => { |
| 189 | if (!acc.is_valid) return false; |
| 190 | if ( |
| 191 | acc.error_count >= 3 && now - acc.last_used < 300_000 /*5 min*/ |
| 192 | ) return false; |
| 193 | const agent = acc.agents.find((a) => allowed.includes(a.id)); |
| 194 | if (!agent) return false; |
| 195 | acc.selected_agent_id = agent.id; |
| 196 | return true; |
| 197 | }); |
| 198 | if (!candidates.length) return undefined; |
| 199 | candidates.sort((a, b) => |
| 200 | (a.last_used - b.last_used) || (a.error_count - b.error_count) |
| 201 | ); |
| 202 | const chosen = candidates[0]; |
| 203 | chosen.last_used = now; |
| 204 | return chosen; |
| 205 | } |
| 206 | |
| 207 | // ---------------------------------------------------------------------------- |
| 208 | // Model discovery – run once at startup |