| 94 | argsSchema = Args; |
| 95 | |
| 96 | async execute(args: z.infer<typeof Args>, _ctx: ToolContext): Promise<ToolResult> { |
| 97 | const timeoutMs = (args.timeout_seconds ?? 6) * 1000; |
| 98 | const targets = args.ecosystems ?? ['npm', 'pip', 'huggingface', 'github']; |
| 99 | |
| 100 | const results: EcoResult[] = await Promise.all(targets.map(async (eco) => { |
| 101 | const spec = ECOSYSTEMS[eco]!; |
| 102 | const probed = await Promise.all(spec.candidates.map(async (c) => { |
| 103 | const { reachable, latencyMs } = await probe(c.probeUrl, timeoutMs); |
| 104 | return { label: c.label, value: c.value, latencyMs, reachable, official: c.official ?? false }; |
| 105 | })); |
| 106 | // Rank: reachable first, then lowest latency. |
| 107 | probed.sort((a, b) => { |
| 108 | if (a.reachable !== b.reachable) return a.reachable ? -1 : 1; |
| 109 | return (a.latencyMs ?? Infinity) - (b.latencyMs ?? Infinity); |
| 110 | }); |
| 111 | return { ecosystem: eco, ranked: probed }; |
| 112 | })); |
| 113 | |
| 114 | const lines: string[] = ['# Network optimization report', '']; |
| 115 | const plan: Array<{ eco: string; value: string }> = []; |
| 116 | |
| 117 | for (const r of results) { |
| 118 | lines.push(`## ${r.ecosystem}`); |
| 119 | for (const c of r.ranked) { |
| 120 | const lat = c.reachable ? `${c.latencyMs} ms` : 'unreachable'; |
| 121 | lines.push(` ${c.reachable ? '✓' : '✗'} ${c.label.padEnd(22)} ${lat}`); |
| 122 | } |
| 123 | const best = r.ranked[0]; |
| 124 | if (!best || !best.reachable) { |
| 125 | lines.push(` → none reachable. Use a proxy / Warp, then re-run.`); |
| 126 | } else { |
| 127 | // Recommend switching only if the winner is a non-official mirror that |
| 128 | // beat the official endpoint, or the official one is unreachable. |
| 129 | const official = r.ranked.find(c => c.official); |
| 130 | const switchTo = !official?.reachable || (!best.official); |
| 131 | if (switchTo && !best.official) { |
| 132 | lines.push(` → RECOMMEND: ${best.label}`); |
| 133 | lines.push(` ${ECOSYSTEMS[r.ecosystem]!.how(best.value)}`); |
| 134 | plan.push({ eco: r.ecosystem, value: best.value }); |
| 135 | } else { |
| 136 | lines.push(` → official endpoint is fine (fastest reachable).`); |
| 137 | } |
| 138 | } |
| 139 | lines.push(''); |
| 140 | } |
| 141 | |
| 142 | if (args.apply && plan.length > 0) { |
| 143 | lines.push('## Applied'); |
| 144 | for (const p of plan) { |
| 145 | try { |
| 146 | const msg = await this.applyOne(p.eco, p.value); |
| 147 | lines.push(` ✓ ${p.eco}: ${msg}`); |
| 148 | } catch (e: any) { |
| 149 | lines.push(` ✗ ${p.eco}: ${e.message}`); |
| 150 | } |
| 151 | } |
| 152 | lines.push(''); |
| 153 | lines.push('Note: HF_ENDPOINT and proxy env vars can only be *suggested* — a tool'); |